为什么LazyInitializationException会在这里发生?

时间:2011-12-04 13:34:37

标签: hibernate jpa-2.0 ejb-3.1

所以我的这个实体有FetchType.LAZY集合:

@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;

}

我有以下服务:

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;
    }

}

现在,我正试图从CDI bean中调用ServiceB#load,如下所示:

@Named
@SessionScoped
public class void WebController implements Serializable {

    @EJB        
    private ServiceC service;

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

但是当我接到 ServiceC entity.getLazyCollection.isEmpty()来电时,我会得到LazyInitializationException: illegal access to loading collection。我不明白为什么。

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

我甚至试图覆盖ServiceA#loadEntity中的ServiceC方法来调用entity.getLazyCollection()来触发数据库的实际加载,但我仍然得到LazyInitializationException

1 个答案:

答案 0 :(得分:1)

基础异常为EntityNotFoundException

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