Eager loading OneToMany in Hibernate with JPA2
I have a simple @OneToMany
between Person
and Pet
entities:
@OneToMany(mappedBy="owner", cascade=CascadeType.ALL, fetch=FetchType.EAGER)
public Set<Pet> getPets() { return pets; }
I would like to load all Person
s with associated Pet
s. So I came up with this (inside a test class):
@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());
}
}
Howeve开发者_如何学Pythonr, turning the SQL logging on shows, that it executes 3 queries (having 2 Persons in the DB).
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=?
Any tips?
Thanks Gergo
Instead of
SetJoin<Person, Pet> join = p1.join(Person_.pets);
one should write
p1.fetch(Person_.pets);
精彩评论