所以我有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
。
你在使用JTA EntityManager嗎? –
不確定,我認爲它是由Hibernate實現的,因爲持久化提供程序是'Hibernate'。 – jFrenetic
你如何獲得'EntityManager'? –