gpt4 book ai didi

java - 仅选择实体集合的子集

转载 作者:行者123 更新时间:2023-12-01 17:46:08 28 4
gpt4 key购买 nike

如果我有一个包含 @OneToMany 的实体,使用 JPA 如何选择该实体以及相关子实体的子集?我无法使用 @Where@Filter 注释。

更多详情
我正在将我们的商业模式转化为更通用的东西,所以不用担心这个例子在现实生活中没有意义。但是查询有很多(比这个示例更多)左连接获取情况。 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 的 parent (金发 = true)。

必须执行什么查询才能过滤掉不符合条件的相关子实体?

我试图避免这样做:查询父级,为每个父级查询子级匹配条件。
编辑
经过更多测试后,我发现这仅在运行测试时不起作用,即问题在于在单元测试中使用 H2 DB 获得预期结果。当使用实际的 MySQL 实例运行时,该查询工作正常。

最佳答案

你不需要@Query(至少对于像这样的简单查询),如果你使用spring-data-jpa,你可以只编写一个像这样的方法这在你的存储库类中

List<Parent> findByChildrenSet_Blonde(boolean isBlonde)

spring-data 将通过查看方法名称来为您制定并执行查询。 _ 表示依赖类字段

现在你可以像这样调用这个函数

findByChildrenSet_Blonde(true)

你也可以写

List<Parent> findByChildrenSet_BlondeTrue()

关于java - 仅选择实体集合的子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60863789/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com