I've got a schema with a series of OneToMany associations, where the hierarchy is Farm -> Field -> RegionGroup -> Region and need to be able to query based upon values in Farm, Field and Region. The following simple construct works;
org.hibernate.Criteria criteria = getSessionFactory().getCurrentSession().createCriteria(Farm.class)
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
.add(Restrictions.in("id", farmIds))
.createCriteria("fields").add(Restrictions.in("id", fieldIds))
.createCriteria("regionGroups")
.createCriteria("regions").add(Restrictions.in("nutrientId", nutrientIds));
return criteria.list();
However, when I then try to account for empty lists being supplied in the filters, the Restrictions are no longer being applied and I get back a resultset containing every Farm, Field and Region. I'm sure it's a matter of sequencing the Criteria instances returned, but I'm tying myself up in knots trying different combinations and getting nowhere fast. Anyone got a suggestion to save my sanity?
org.hibernate.Criteria criteria = getSessionFactory().getCurrentSession().createCriteria(Farm.class)
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
if (!farmIds.isEmpty()){
criteria.add(Restrictions.in("id", farmIds));
}
org.hibernate.Criteria fieldCriteria = criteria.createCriteria("fields");
if (!fieldIds.isEmpty()){
fieldCriteria.add(Restrictions.in("id", fieldIds));
}
if (!nutrientIds.isEmpty()){
fieldCriteria.createCriteria("regionGroups")
.createCriteria("regions").add(Restrictions.in("nutrientId", nutrientIds));
}
return criteria.list();