Criteria api equivalent for joining child with parent

青春壹個敷衍的年華 提交于 2019-12-12 02:26:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!