版本:Hibernate 3.3
您好, 我有2个简单的模型:
class Parent {
Long id; //auto generated sequence and primary key
String name;
Set<Child> children;
}
class Child {
Long id;
String name;
Parent parent;
}
使用以下hbm:
<class name="my.Parent" table=PARENT">
<id name="id" column="PARENT_ID" type="java.lang.Long">
<property name="name" column="NAME" type="java.lang.String">
<set name="children" table="CHILDREN" inverse="true">
<key><column name="PARENT_ID" not-null="true" /></key>
<one-to-many class="my.Child" />
</set>
</class>
<class name="my.Child" table=CHILD">
<composite-id>
<key-many-to-one name="parent" column="PARENT_ID" class="my.Parent" />
<key-property name="id" column="CHILD_ID" type="java.lang.Long" />
</composite-id>
<property name="name" column="NAME" type="java.lang.String">
</class>
我想要实现的目标是:“选择父母姓名为'John'的所有孩子。我无法弄清楚如何为看起来像这样的hql编写Criteria api等价物:
SELECT child
FROM Child as child join child.parent
where parent.name = 'John'
我尝试了下面的一个,但它没有生成预期的连接查询:
Criteria c = session.createCriteria(Child.class);
c.createCriteria("parent").add(Restrictions.eq("name", "John");
c.list();
有人能看出我做错了吗?
任何想法都将不胜感激。
答案 0 :(得分:0)
使用JPA 2.0条件API,您可以:
criteriaBuilder cb =...
CriteriaQuery<child> q=....
Root<child> entity= .....
Join<child, parent> o = entity.join(child_.parent);
Path<parent> c = entity.get(child_.parent);
Path<String> name = c.get(parent_.name);
.... where( cb.equal(name, "john"));