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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With