gpt4 book ai didi

java - 使用 JPA2 在 Hibernate 中急切加载 OneToMany

转载 作者:行者123 更新时间:2023-11-30 05:12:42 25 4
gpt4 key购买 nike

我在 PersonPet 实体之间有一个简单的 @OneToMany:

@OneToMany(mappedBy="owner", cascade=CascadeType.ALL, fetch=FetchType.EAGER)
public Set<Pet> getPets() { return pets; }

我想加载所有带有关联PetPerson。所以我想出了这个(在测试类中):

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class AppTest {

@Test
@Rollback(false)
@Transactional(readOnly = false)
public void testApp() {
CriteriaBuilder qb = em.getCriteriaBuilder();
CriteriaQuery<Person> c = qb.createQuery(Person.class);
Root<Person> p1 = c.from(Person.class);
SetJoin<Person, Pet> join = p1.join(Person_.pets);
TypedQuery<Person> q = em.createQuery(c);
List<Person> persons = q.getResultList();
for (Person p : persons) {
System.out.println(p.getName());
for (Pet pet : p.getPets()) {
System.out.println("\t" + pet.getNick());
}
}

但是,打开 SQL 日志记录显示它执行了 3 个查询(数据库中有 2 个人)。

Hibernate: select person0_.id as id0_, person0_.name as name0_, person0_.sex as sex0_ from Person person0_ inner join Pet pets1_ on person0_.id=pets1_.owner_id
Hibernate: select pets0_.owner_id as owner3_0_1_, pets0_.id as id1_, pets0_.id as id1_0_, pets0_.nick as nick1_0_, pets0_.owner_id as owner3_1_0_ from Pet pets0_ where pets0_.owner_id=?
Hibernate: select pets0_.owner_id as owner3_0_1_, pets0_.id as id1_, pets0_.id as id1_0_, pets0_.nick as nick1_0_, pets0_.owner_id as owner3_1_0_ from Pet pets0_ where pets0_.owner_id=?

有什么建议吗?

谢谢格尔戈

最佳答案

而不是

SetJoin<Person, Pet> join = p1.join(Person_.pets);

应该写

p1.fetch(Person_.pets);

关于java - 使用 JPA2 在 Hibernate 中急切加载 OneToMany,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2849213/

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