Hibernate checking all elements equal in collection

I have two entities ie Person and Activity. Activity has property status and Person entity contains collection of activities. I'd like to get a list of persons that have all activities with status 'Done'.

   Criteria crit = s.createCriteria(Person.class);
   crit.createAlias("activities", "act").add(Restrictions.eq("act.status","Done"));

But this return all object with at least one activity with status done. I 'd like to retrive list of person with all activities status set to Done. Can anyone help me?


Think in negate it. Retrieve those whose have activities and none is in state different of Done . Then you can simply add the maxResults() or list.get(0) (Bear in mind that might contain no person).


// open hibernate session
Query query = session.createQuery("Select p from Persons p inner join p.activities a where a.status = :code");
query.setParameter("code", "Done");
List results = query.list();

// close session

for (int i = 0; i < results.size(); ){
  Person person = results.get(i);
  List<Activity> activities = person.getActivities();
  for (int j = 0; j < activities.size(); j++){
    if (!activities.code.equals("Done")){
      results.remove(i);
      break;
    } // end if
  } // end for j
  i++;
} // end for i

This should do the trick. Note that if you have lazy load, you may need to add "fetch" keyword in your Hibernate query. Here is a useful link for joins: http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html#queryhql-joins


Here is how you can do it with Criteria :

Criteria crit = s.createCriteria(Person.class);

DetachedCriteria sub = DetachedCriteria.forClass(Person.class);
sub.createAlias("activities","act");
sub.add(Restrictions.ne("act.status","Done"));
sub.setProjection(Projections.property("id");

crit.add(Property.forName("id").notIn(sub);

Kinda late but I hope I can help someone who still struggles with this as I did.

链接地址: http://www.djcxy.com/p/10768.html

上一篇: Spring自动装配使用注释和属性文件中定义的类型?

下一篇: Hibernate检查集合中的所有元素相等