[英]how can to resolve org.hibernate.LazyInitializationException?
org.hibernate.LazyInitializationException :无法延迟初始化角色集合:com.t4bt.gov.persistence.entities.Experts.institutaionList,没有会话或会话被关闭
You provide very little details in your question (code?), so it will have to be a generalized answer regarding lazy loading. 您在问题中提供的细节很少(代码?),因此它必须是关于延迟加载的通用答案。 In the future, if you want answers, please provide concrete information about the actual problem, as well as descriptions as to what you have tried to solve it.
将来,如果您需要答案,请提供有关实际问题的具体信息,以及有关您试图解决的问题的描述。
A LazyInitialization occurs when you try to access a lazily loaded property after the session is closed (which is usually after the transaction has ended). 当您在会话关闭后(通常是在事务结束之后)尝试访问延迟加载的属性时,就会发生LazyInitialization。 The way lazy initalization works is that it doesn't fetch the lazily initialized properties when you fetch the object, but when you actually try to access it, Hibernate does another query to the database to fetch it.
惰性初始化的工作方式是,当您获取对象时,它不会获取延迟初始化的属性,但是当您实际尝试访问它时,Hibernate会对数据库进行另一个查询以获取它。
The following would produce such an error: 以下将产生这样的错误:
public class Something {
[...]
@OneToMany(fetch = FetchType.LAZY)
private List<SomethingElse> somethingElse;
public List<SomethingElse> getSomethingElse() {
return somethingElse;
}
}
public class SomethingDao {
@Inject
private EntityManager em;
@Transactional
public Something getById(final Integer id) {
return em.find(Something.class, id);
}
}
public class SomethingService {
@Inject
private SomethingDao dao;
public List<SomethingElse> getSomethingElseForSomething(final Integer somethingId) {
final Something something = dao.getById(somethingId);
return something.getSomethingElse() //Throws LazyInitializationException
}
}
Here the transaction (and thus the session) only exists in the dao-class. 在这里,事务(以及会话)仅存在于dao类中。 Once leaving the dao-method, the session is gone.
离开dao方法后,会话就消失了。 So, when you try to access a lazy-loaded property in the service, it will fail when Hibernates tries to contact the session in order to retrieve it.
因此,当您尝试访问服务中的延迟加载属性时,当Hibernate尝试联系会话以检索它时,它将失败。
To avoid this, there are several possibilities. 为了避免这种情况,有几种可能性。
@OneToMany(fetch = FetchType.EAGER)
The property is no longer lazy-loaded, so no more problems. @OneToMany(fetch = FetchType.EAGER)
该属性不再延迟加载,因此不再有问题。 @Transactional
to Service-method. @Transactional
添加到Service-method。 Then the call to getSomethingElse()
would be in the same transaction as the fetching of the Something-object, and the session will still be alive when doing so. getSomethingElse()
的调用将与获取Something对象的事务处于同一事务中,并且这样做时会话仍将保持活动状态。 getSomethingElse()
in the Dao-method. getSomethingElse()
的调用。 Then it will initialize the property (fetch it from the database) before leaving the Dao-class (and the transaction), and it will be available outside the transaction, with no need to communicate with the session in order to retrieve it.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.