Fetching objects of class B stored in a list inside class A with Hibernate Criteria

百般思念 提交于 2019-12-13 03:04:03

问题


I have two classes, User and Notification with following association:

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

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

I'm trying to fetch list of notification which are sent before a specific time and belong to a specific user. I've tried to accomplish this with Hibernate Criteria:

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();

The problem is that originally i defined the criteria for class 'User' but final result is of class 'Notification' so I get a casting exception.

Is it possible to solve this problem?


回答1:


This is the expected result. You are running the query on the User class so, the output would be a collection of User and not notification

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;

}

Or the other way of doing it would be to use Filters. You can find a tutorial on filters here



来源:https://stackoverflow.com/questions/18042596/fetching-objects-of-class-b-stored-in-a-list-inside-class-a-with-hibernate-crite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!