所以我有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'? –