Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate checking all elements equal in collection

Tags:

java

hibernate

I have two entities i.e 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?

like image 654
mkowal87 Avatar asked May 17 '12 21:05

mkowal87


3 Answers

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.

like image 67
V. Dimitrov Avatar answered Oct 27 '22 03:10

V. Dimitrov


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).

like image 27
ssedano Avatar answered Oct 27 '22 04:10

ssedano


// 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

like image 1
Silviu Burcea Avatar answered Oct 27 '22 03:10

Silviu Burcea