![](/img/trans.png)
[英]Hibernate: Select entities where collection contains all of the specified valus
[英]Select only a subset of an Entities Collection
如果我有一个包含@OneToMany
的实体,使用 JPA 如何选择实体和相关子项的子集? 我不能使用@Where
或@Filter
注释。
更多细节
我正在将我们的商业模式转化为更一般的东西,所以不要担心这个例子对 IRL 没有意义。 但是 Query 有很多(比这个例子更多)的left join fetch
案例。 Friend 没有关系,只有一个字符串名称。
@Entity
public class Parent {
@Id
@GeneratedValue
private int parentId;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "friendId")
private Friend friends;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "parent", cascade = CascadeType.ALL)
private Set<Child> childrenSet = new HashSet<>();
}
@Entity
public class Child {
@Id
@GeneratedValue
private int childId;
private boolean blonde;
@ManyToOne(fetchType.LAZY, cascade = CascadeType.ALL)
private Parent parent;
}
@Query( "SELECT p " +
"FROM Parent p " +
"JOIN FETCH p.friends f " +
"LEFT JOIN FETCH p.childrenSet c " +
"WHERE f.name IS NOT NULL " +
"AND c.blonde = true")
List<Parent> getParentsWithListOfOnlyBlondeChildren();
测试班
@Transactional
@SpringBootTest
@RunWith(SpringRunner.class)
@DataJpaTest
public class TestParentRepo {
@PersistenceContxt
private EntityManager entityManager;
@Autowired
private ParentRepo parentRepo;
@Before
public void setup() {
Child c1 = new Child();
c1.setBlonde(true);
Child c2 = new Child();
c2.setBlonde(false);
Friend friend1 = new Friend();
friend1.setName("friend1");
Set<Child> children = new HashSet<>();
children.add(c1);
children.add(c2);
Parent parent1 = new Parent();
parent1.setFriends(friend1);
c1.setParent(parent1);
c2.setParent(parent1);
entityManager.persist(friend1);
entityManager.persist(parent1);
entityManager.persist(c1);
entityManager.persist(c2);
entityManager.flush();
entityManager.clear();
}
@Test
public void runTest() {
List<Parent> parent = parentRepo.getParentsWithListOfOnlyBlondeChildren();
System.out.println(parent);
}
}
现在,当调试我得到的是在集合中具有两个孩子的父对象。 我想要的是只有 c1 (blonde = true) 的父级。
查询必须是什么才能过滤掉不符合条件的相关子实体?
我试图避免这样做:查询父级,为每个父级查询子级匹配条件。
编辑
经过更多测试,我发现这仅在运行测试时不起作用,即问题在于在单元测试中使用 H2 DB 获得预期结果。 当使用实际的 MySQL 实例运行时,查询工作正常。
您不需要@Query
(至少对于像这样的简单查询),如果您使用的是spring-data-jpa
,则可以在存储库类中编写这样的方法
List<Parent> findByChildrenSet_Blonde(boolean isBlonde)
spring-data 将通过查看方法名称为您制定和执行查询。 _
是表示依赖类字段
现在你可以像这样调用这个函数
findByChildrenSet_Blonde(true)
你也可以写
List<Parent> findByChildrenSet_BlondeTrue()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.