Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate Criteria join query one to many

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"); 
like image 495
hellzone Avatar asked Jul 17 '13 13:07

hellzone


People also ask

How do you write join query in Hibernate using criteria?

Criteria in Hibernate can be used for join queries by joining multiple tables, useful methods for Hibernate criteria join are createAlias(), setFetchMode() and setProjection() Criteria in Hibernate API can be used for fetching results with conditions, useful methods are add() where we can add Restrictions.


1 Answers

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); 
like image 115
JB Nizet Avatar answered Sep 20 '22 16:09

JB Nizet