渴望用JPA2在Hibernate中加载OneToMany

时间:2010-05-17 13:03:15

标签: java hibernate jpa eager-loading jpa-2.0

我在@OneToManyPerson个实体之间有一个简单的Pet

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

我想加载所有Person个关联的Pet s。所以我想出了这个(在测试类中):

@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=?

任何提示?

由于 Gergo

1 个答案:

答案 0 :(得分:2)

而不是

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

应该写

p1.fetch(Person_.pets);