Hibernate Criteria连接查询一对多 [英] Hibernate Criteria join query one to many
问题描述
我有一个Cat类和一个Owner类。猫有一个主人,但主人可以有很多猫。我想查询的是让所有拥有蓝眼睛猫的所有者。
class Cat {
业主; //从Owner.id引用
String eyeColor;
}
类所有者{
列表< Cat> catList;
}
我尝试了一些代码,但我真的不知道该怎么做。
Criteria criteria = getCurrentSession()。createCriteria(cat.getClass(),cat);
criteria.createAlias(cat.owner,owner);
criteria.add(Restrictions.eq(cat.eyeColor,blue);
然而,这里并没有丢失所有内容,因为您的关联是双向的,所以您只需要相当于HQL查询
从所有者中选择不同的所有者
加入owner.cats cat
其中cat.eyeColor ='blue'
这是
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);
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 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);
这篇关于Hibernate Criteria连接查询一对多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!