【发布时间】:2020-03-26 08:58:56
【问题描述】:
如果我有一个包含@OneToMany 的实体,使用 JPA 如何选择实体以及相关子项的子集?我不能使用@Where 或@Filter 注释。
更多详情
我正在将我们的商业模式翻译成更通用的东西,所以不要担心这个例子没有意义 IRL。但是查询有很多(比这个例子更多)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);
}
}
现在在调试时,我 GET 是集合中包含两个子对象的父对象。我想要是只有 c1 的父母(金发女郎 = true)。
查询必须是什么才能过滤掉不符合条件的相关子实体?
我试图避免这样做:查询父母,为每个父母查询孩子匹配标准。
编辑
经过更多测试后,我发现这仅在运行测试时不起作用,即问题在于在单元测试中使用 H2 DB 获得预期结果。使用实际 MySQL 实例运行时,查询工作正常。
【问题讨论】: