2013-08-04 66 views
0

我有两个班,用户与以下联系通知获取对象

public class User { 
    private Long id; 
    private List<Notification> notifications; 
} 

public class Notification { 
    private Long id; 
    private Date date; 
} 

我试图获取的通知列表它们在特定时间之前发送并属于特定用户。我试过用Hibernate的标准来实现:

Criteria criteria = session.createCriteria(User.class).add(Restrictions.eq("id", "123")); 
criteria.createAlias("notifications", "notif"); 
criteria.add(Restrictions.lt("notif.date", calendar.getTime())); 
Collection<Notification> result = criteria.list(); 

的问题是,原来我定义为类“用户”,但最终的结果是类“通知”的标准,所以我得到的铸件例外。

有没有可能解决这个问题?

回答

0

这是预期的结果。您正在运行的User类查询的话,输出会是用户的集合,而不是通知

public List<Notification> getNotifications(Long id){ 

//Start the transaction 

//do some error handling and transaction rollback 
User user = session.createQuery("from User where id = :id").setParameter("id", id).uniqueParameter(); 

List<Notification> notifications = new ArrayList<Notification>(); 
for (Notification notification : user.getNotifications()){ 
    if (notification.getDate.before(calendar.getTime()){ 
     notifications.add(notification); 
    } 
} 
//commit the transaction 
//close the session 
return notifications; 

}

或做它是使用过滤器的其他方式。你可以找到一个过滤教程here

+0

谢谢,说我想获取通知。我如何操纵代码来实现这一目标? – mdoust

+0

已更新答案 –

+0

因此,您在此建议的是使用HQL获取用户对象,然后获取通知列表并根据特定日期过滤列表。它应该可以正常工作,但我想要做的就是明确使用Criteria。它甚至有可能这样做吗? – mdoust