我有一些单向 @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.someProperty=10
和 child2.someProperty=20
获取所有家长。有人可以帮忙吗?
我尝试使用加入:
Root<Parent> root = criteria.from(Parent.class);
ListJoin<Parent, Child1> join = root.join(Parent_.childList1);
criteriaBuilder.equal(join.get(Child1_.someProperty), 10);
但是,这会为每个 Child1
返回一个 Parent
:
Parent----Child1(someProperty=10)
Parent----Child1(someProperty=10)
我希望结果是:
/Child1(someProperty=10)
/
Parent/---Child1(someProperty=10)
\
\
\Child2(someProperty=20)
有人可以帮忙解决这个问题吗?我更喜欢 JPA Criteria,不过 JPQL 也不错。
如果有帮助的话,我准备对我的实体结构进行微小的更改(微小更改,例如使关系成为双向的?)
谢谢。
顺便说一句,我使用 hibernate 作为 JPA 实现。
最佳答案
您必须在查询中使用setDistinct(true)
。
您获得的结果是逐行映射到实体的有效联接结果。添加不同的将启用根聚合,导致我的父级拥有 N
个子级,因为我相信这就是您所期望的。
关于java - 根据 JPA 2 中的子参数过滤父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47009335/