使用JPA(EntityManager)和Hibernate。

我有一个带有3个集合的类,一个集合具有FetchType.EAGER,另外两个集合具有LAZY。如果我将其中的3个放入EAGER,我会得到一个例外,因为它只能有一个。这样,当我尝试使用LAZY列表之一时,出现异常:

no session or session was closed: javax.faces.el.EvaluationException: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role:


那么,当我索取2个收藏夹时,如何获得它们?

我的课:

public class Event implements....
....
....
@ElementCollection(fetch = FetchType.LAZY)
@CollectionTable(name="friendsList")
private List<Long> friends;
@ElementCollection(fetch = FetchType.LAZY)
@CollectionTable(name="carsList")
private List<Long> cars;
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name="housesList")
private List<Long> houses;


我尝试了这个但仍然无法正常工作

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public IEvent synchronizeCarsList(IEvent companyToSynchronize){
    if(companyToSynchronize == null)
        throw new IllegalArgumentException();
    if(entityManager != null) {
        List<Long> cars = companyToSynchronize.getSelectedCarsIdList();

    }
    return companyToSynchronize;
}


编辑:
当我在一个实体中拥有多个EAGER时(或我从日志中了解的内容),部署时会发生异常

Caused by: org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags
at org.hibernate.loader.BasicLoader.postInstantiate(BasicLoader.java:94) [:3.6.6.Final]
at org.hibernate.loader.entity.EntityLoader.<init>(EntityLoader.java:119) [:3.6.6.Final]
at org.hibernate.loader.entity.EntityLoader.<init>(EntityLoader.java:71) [:3.6.6.Final]
at org.hibernate.loader.entity.EntityLoader.<init>(EntityLoader.java:54) [:3.6.6.Final]
at org.hibernate.loader.entity.BatchingEntityLoader.createBatchingEntityLoader(BatchingEntityLoader.java:133) [:3.6.6.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.createEntityLoader(AbstractEntityPersister.java:1914) [:3.6.6.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.createEntityLoader(AbstractEntityPersister.java:1937) [:3.6.6.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.createLoaders(AbstractEntityPersister.java:3205) [:3.6.6.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.postInstantiate(AbstractEntityPersister.java:3191) [:3.6.6.Final]
at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:348) [:3.6.6.Final]
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1872) [:3.6.6.Final]
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:906) [:3.6.6.Final]
... 105 more


问候。

最佳答案

仅分配延迟加载的Collection的值不足以触发加载。您将获得的只是对代理的引用。这就是在事务外部进行访问将失败的原因。

仍在事务中时,在.size()上调用Collection会触发加载,其他任何需要访问实际内容的方法也将触发加载。

10-06 15:35