HQL一对多在单个查询中选择单个对象

时间:2016-08-23 10:20:39

标签: hibernate hql

我想要检索具有“内部”对象C的类A的对象。

我有一个A类:

public class A {
...
@OneToMany(mappedBy = "classA")
private List<B> listOfB;

}

B级:

public class B {

...
@ManyToOne
@JoinColumn(name = "A_FK")
private A AObject;

@OneToMany(mappedBy = "classB")
private List<C> ListOfC;

}

和C班:

public class C {
...

private String CId;

@ManyToOne
@JoinColumn(name = "B_FK")
private B BObject;


}

说明:我有对象A,它有对象列表B(一个B对象只能在一个对象A中),每个对象B里面有几个对象C(对象C只能在一个B中)。

如何使用单个HQL查询检索对象A,知道对象C的ID?

2 个答案:

答案 0 :(得分:0)

尝试此HQL查询:

select a from A as a 
    join a.listOfB as b
    join b.listOfC as c 
    where c.CId = '1234'

完整的java示例:

Query query = this.session.createQuery("select a from A as a join a.listOfB as b join b.listOfC as c where c.CId = :id");
query.setString("id", "1234"); 
A a = (A)query.uniqueResult();

答案 1 :(得分:0)

事实证明,我不必使用任何连接,因此hibernate将自己连接表。此示例的工作查询:

select Bclass.AObject 
from B as Bclass 
where Bclass.id = (select Cclass.Bclass.id FROM C Cclass WHERE c.Id=:Id)