Hibernate 为什么LazyInitializationException在这里发生?

Hibernate 为什么LazyInitializationException在这里发生?,hibernate,jpa-2.0,ejb-3.1,Hibernate,Jpa 2.0,Ejb 3.1,因此,我有一个带有FetchType.LAZYcollection的实体: @Entity public class Entity implements Serializable { @OneToMany(mappedBy = "entity", fetch=FetchType.LAZY) private List<OtherEntity> lazyCollection; //getters and setters } @Entity public cl

因此,我有一个带有
FetchType.LAZY
collection的实体:

@Entity
public class Entity implements Serializable {

    @OneToMany(mappedBy = "entity", fetch=FetchType.LAZY)
    private List<OtherEntity> lazyCollection;

    //getters and setters
}

@Entity
public class OtherEntity implements Serializable {

    @ManyToOne
@JoinColumn(name = "entity", nullable = false)
private Entity entity;

}
但是当我调用
ServiceC
entity.getLazyCollection.isEmpty()
时,我得到了
LazyInitializationException:非法访问加载集合
。我不明白为什么

这是否意味着加载后,实体以某种方式变得分离


我甚至试图覆盖
ServiceC
中的
ServiceA#loadEntity
方法调用
entity.getLazyCollection()
来触发从数据库的实际加载,但我仍然得到这个
lazyinstalizationexception
底层异常是
EntityNotFoundException


OtherEntity
与数据库中未找到的
SomeOtherEntity
具有强制的一对一关联。我没有在日志中看到它,因为登录我们的项目没有正确设置。除此之外,
LazyInitializationException
在这种情况下似乎很奇怪。看起来Hibernate将
EntityNotFoundException
包装到
LazyInitializationException
中。我不清楚这样做的原因。

您使用的是JTA EntityManager吗?不确定,我认为它是由Hibernate实现的,因为持久性提供程序是
Hibernate
。您如何通过@PersistenceContext注释获得
EntityManager
(和persistence.xml配置为使用
Hibernate
作为持久性提供程序)。好吧,这似乎很奇怪,因为您使用的是JTA容器管理的EntityManager。您应该处于由ServiceC加载(-)方法调用启动的活动事务中,并且可以访问集合。Hibernate的一个神秘偏差;-)
public class ServiceA implements Serializable {
    public Entity loadEntity(Long entityId) {
        return em.find(Entity.class, entityId);
    }
}

public class ServiceB extends ServiceA {
    public Map<? extends X, ? extends Y> load(Long entityId) {
        Entity entity = loadEntity(entityId);
        //play with entity and fill the map with required data
        return prepareMap(entity, map);
    }

    //meant to be overriden in inheriting services
    protected Map<? extends X, ? extends Y> prepareMap(Entity entity,
            Map<? extends X, ? extends Y> map) { return map; }
}

@Stateless
public class ServiceC extends ServiceB {

    @Override
    protected Map<? extends X, ? extends Y> prepareMap(Entity entity,
            Map<? extends X, ? extends Y> map) {
        if (entity.getLazyCollection() != null
                && !entity.getLazyCollection.isEmpty()) {
            // play with entity and put some other data to map
        }
        return map;
    }

}
@Named
@SessionScoped
public class void WebController implements Serializable {

    @EJB        
    private ServiceC service;

    public void loadEntity(Long entityId) {
        service.load(entityId);
    }
}