2011-12-04 53 views
2

所以我有FetchType.LAZY收集本单位:为什么LazyInitializationException在这里发生?

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

} 

现在,我想打电话给ServiceB#load从CDI豆这样的:

@Named 
@SessionScoped 
public class void WebController implements Serializable { 

    @EJB   
    private ServiceC service; 

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

但是当我到达ServiceC拨打,我得到LazyInitializationException: illegal access to loading collection。我不明白为什么。

这是否意味着加载后,实体莫名其妙地分离?

我甚至试图重写ServiceA#loadEntity方法ServiceC调用entity.getLazyCollection()从数据库触发器实际负荷,但我仍然得到这个LazyInitializationException

+0

你在使用JTA EntityManager吗? –

+0

不确定,我认为它是由Hibernate实现的,因为持久化提供程序是'Hibernate'。 – jFrenetic

+0

你如何获得'EntityManager'? –

回答

1

潜在的例外是EntityNotFoundException

OtherEntitySomeOtherEntity有强制性的一对一关联,在数据库中找不到该对象。我没有在日志中看到它,因为登录我们的项目没有正确设置。除此之外,LazyInitializationException在这种情况下似乎很奇怪。看起来像休眠包装EntityNotFoundExceptionLazyInitializationException。这样做的原因对我而言并不明确。

+0

休眠神秘的偏差之一;-) –