Search code examples
javahibernatecriteria

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


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?


Solution

  • 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