问题
Version: Hibernate 3.3
Hi, I have 2 simple models:
class Parent {
Long id; //auto generated sequence and primary key
String name;
Set<Child> children;
}
class Child {
Long id;
String name;
Parent parent;
}
with the following 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>
What I want to achieve is this: "select all children whose parent's name is 'John'. I am not able to figure out how to write Criteria api equivalent for a hql that looks like this:
SELECT child
FROM Child as child join child.parent
where parent.name = 'John'
I tried the below one but its not generating the expected join query:
Criteria c = session.createCriteria(Child.class);
c.createCriteria("parent").add(Restrictions.eq("name", "John");
c.list();
Could anybody see what am I doing wrong?
Any ideas would be greatly appreciated.
回答1:
Using JPA 2.0 criteria API, you could do :
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"));
来源:https://stackoverflow.com/questions/6488356/criteria-api-equivalent-for-joining-child-with-parent