我有这样的实体结构(省略了注释和标识符):
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'
答案 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
)
答案 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;
}