Java 基于JPA2中的子参数筛选父项
我有一些单向的Java 基于JPA2中的子参数筛选父项,java,hibernate,jpa,criteria,jpql,Java,Hibernate,Jpa,Criteria,Jpql,我有一些单向的@OneToMany关系如下: @Entity @Table(name = "Parent") public class Parent { @OneToMany @JoinColumn(name = "ParentID") private List<Child1> childList1; @OneToMany @JoinColumn(name = "ParentID") private List<Child2&g
@OneToMany
关系如下:
@Entity
@Table(name = "Parent")
public class Parent {
@OneToMany
@JoinColumn(name = "ParentID")
private List<Child1> childList1;
@OneToMany
@JoinColumn(name = "ParentID")
private List<Child2> childList2;
}
@Entity
@Table(name = "Child1")
public class Child1 {
private int someProperty;
// other properties
}
@Entity
@Table(name = "Child2")
public class Child2 {
private int someProperty;
// other properties
}
但是,对于每个Child1
,这将返回一个Parent
:
Parent----Child1(someProperty=10)
Parent----Child1(someProperty=10)
我希望结果是:
/Child1(someProperty=10)
/
Parent/---Child1(someProperty=10)
\
\
\Child2(someProperty=20)
谁能帮我一下吗?我更喜欢JPA标准,不过JPQL还可以。
如果有帮助的话,我准备对我的实体结构做一些小的改变(小的改变,比如使关系双向?) 谢谢
顺便说一下,我使用hibernate作为JPA实现。您必须在查询中使用
setDistinct(true)
。
您获得的结果是有效的联接结果,逐行映射到实体。添加distinct将启用根聚合,从而使我的父级具有
N
子级,因为我相信这正是您所期望的。@JBNizet恐怕这无法解决问题。为了简洁起见,我省略了Child1
中的一些属性,这些属性可能有所不同。与具有两个Child1
实体的Parent
一样:Child1(someProperty=10,otherProperty=25)
和Child1(someProperty=10,otherProperty=30)
如果您的意思是,查询返回的父对象的子对象不是具有给定子对象属性的父对象,这是不正常的,也是预期的。查询确定返回哪些父级。但是父对象的子对象是父对象的子对象,所有子对象,无论您使用何种查询来选择父对象。如果要筛选子项,则需要一个选择子项而不是父项的查询。@JBNizet My bad,结果证明您是对的。你能把它作为答案贴出来让我接受吗?
/Child1(someProperty=10)
/
Parent/---Child1(someProperty=10)
\
\
\Child2(someProperty=20)