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