等同于将父母加入孩子的标准API [英] Criteria api equivalent for joining child with parent

查看:71
本文介绍了等同于将父母加入孩子的标准API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

版本:Hibernate 3.3

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; 
}

加入以下hbm:

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>

我想要实现的是:选择所有父母姓名为'John'的孩子。我无法弄清楚如何编写相当于hql的Criteria api,如下所示:

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

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.

推荐答案

使用JPA 2.0标准API,您可以执行以下操作:

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

这篇关于等同于将父母加入孩子的标准API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆