JPA - 使用Root,Join在字段上加入获取

时间:2014-09-18 09:55:37

标签: java hibernate jpa join

我有这些类,字段总是延迟加载。

public class Book {
     @ManyToOne(fetch = FetchType.LAZY)
     private Publication publication;

     @OneToMany(fetch = FetchType.LAZY)
     private List<Author> authors;

     @OneToMany(fetch = FetchType.LAZY)
     private List<Genre> genres;
}

public class Publication{
     @OneToMany(fetch = FetchType.LAZY)
     private List<Founder> founders;

}

我想要实现的是连接提取连接。在hql中,它看起来像这样:

FROM Book b LEFT JOIN b.authors LEFT JOIN b.genres LEFT JOIN b.publication p LEFT JOIN p.founders

这是我到目前为止所尝试的但是它无效:

Root<Book> root ...
Join<Book, Publication> publication = root.join("publication");
publication.fetch("founders");
root.fetch("authors");
root.fetch("genres");

以下是异常的原因:

Caused by: javax.persistence.PersistenceException: org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1763)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1677)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1683)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:588)
    at org.hibernate.jpa.criteria.CriteriaQueryImpl$1.buildCompiledQuery(CriteriaQueryImpl.java:336)
    at org.hibernate.jpa.criteria.compile.CriteriaCompiler.compile(CriteriaCompiler.java:147)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:736)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)

1 个答案:

答案 0 :(得分:6)

JPA规范说:

  

a不需要支持多级获取连接   本规范的实施。使用的应用程序   多级获取连接将无法移植。

尝试减少查询中的提取连接并稍后初始化数据(在数据选择之后)。 您可以在同一事务中使用size()或Hibernate.initialize()初始化延迟加载的数据,例如:

publication.getFounders().size();

Hibernate.initialize(publication.getFounders());