2011-12-04 54 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

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