从DB中选择是指定嵌套集合的条件

时间:2013-12-05 23:49:53

标签: java sql hibernate jpa jpa-2.0

我有这样的实体结构(省略了注释和标识符):

   public class A {
      List<B> bList;
    }

    public class B {
      List<C> cList;
    }

    public class C {
      String name;
    }

我如何编写Criteria(或HQL / JPQL查询)来检索A所有C.name等于“Peter”的实例?

即。像这样:

SELECT * FROM A WHERE A.bList.cList.name = 'Peter'

2 个答案:

答案 0 :(得分:0)

运行此(JPQL)并告诉我您的结果:

SELECT DISTINCT a FROM A a
WHERE
EXISTS
( 
    SELECT b FROM B b
    WHERE EXISTS ( SELECT c FROM C c WHERE c.name = "Peter" AND c.b_id = b.b_id )
    AND b.a_id = a.a_id
)
  • 我认为a_id是A的PK
  • b_id是B的PK,b.a_id引用A.a_id
  • c.b_id对B.b_id的引用

答案 1 :(得分:0)

HQL查询应该像

Query query = session.getCurrentSession().createQuery("FROM A AS a WHERE a.bList.cList.name = :cname");
query.setParameter("cname", "Peter");
return query.list();

我假设您的实体关系如下

@Entity
@Table(name = "TABLE_A")
public class A {
@OneToMany(mappedBy="a")
List<B> bList;
}

@Entity
@Table(name = "TABLE_B")
public class B {

@ManyToOne
@JoinColumn(name="a_id")
private A a;

@OneToMany(mappedBy="department")
List<C> cList;

}

@Entity
@Table(name = "TABLE_C")
public class C {

@ManyToOne
@JoinColumn(name="b_id")
private B b;

@Column(name="name")
String name;
}