Hibernate Criteria join query one to many

hellzone picture hellzone · Jul 17, 2013 · Viewed 45.9k times · Source

I have a Cat class and a Owner class. A cat has one owner but an owner can have many cats. What I want to query is get all owners who have a cat with blue eyes.

class Cat {
    Owner owner; //referenced from Owner.id
    String eyeColor;
}

class Owner {
    List<Cat> catList;
}

I tried some codes but I really don't know what to do.

Criteria criteria = getCurrentSession().createCriteria(cat.getClass(), "cat");
criteria.createAlias("cat.owner", "owner");    
criteria.add(Restrictions.eq("cat.eyeColor", "blue");

Answer

JB Nizet picture JB Nizet · Jul 17, 2013

Criteria can only select projections, or the root entity. Not some joined entity. Some queries are thus impossible to express with Criteria (which is one more good reason to use HQL, in addition to much better readability and conciseness).

All is not lost here, though, because your association is bidirectional. So you just need the equivalent of the HQL query

select distinct owner from Owner owner 
join owner.cats cat 
where cat.eyeColor = 'blue'

Which is

Criteria c = session.createCriteria(Owner.class, "owner");
c.createAlias("owner.cats", "cat");
c.add(Restrictions.eq("cat.eyeColor", "blue");
c.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);