[英]In Hibernate JPA how to transparently solve “ failed to lazily initialize a collection of role ” exception
I am migrating a huge project from Eclipselink to Hibernate JPA that running on Wildfly 10.0 我正在将一个巨大的项目从Eclipselink迁移到在Wildfly 10.0上运行的Hibernate JPA
Once moved to Hibernate I got the famous exception " failed to lazily initialize a collection of role " 移到Hibernate之后,我得到了一个著名的例外:“未能懒惰地初始化角色集合”
I found many solutions for this issue like these suggestions on this Question as well as the old OpenSessionInView method. 我发现了许多针对此问题的解决方案,例如关于此Question的这些建议以及旧的OpenSessionInView方法。
But these solutions are somehow outdated, and needs some changes on my running existing code that use eclipselink. 但是这些解决方案已经过时了,需要在我使用eclipselink的现有代码上进行一些更改。
Is their a newer, modern, transparent solution that can save my time ? 他们是可以节省我时间的更新,现代,透明的解决方案吗?
Note : I am not using spring (only JPA and EJB) . 注意 :我没有使用spring(仅JPA和EJB)。
I think you are looking for the hibernate.enable_lazy_load_no_trans
configuration property. 我认为您正在寻找
hibernate.enable_lazy_load_no_trans
配置属性。 But that's an Anti-Pattern. 但这是一个反模式。 Just because other JPA providers use it, it does not mean that it is efficient as well, or it's even appropriate.
仅仅因为其他JPA提供程序正在使用它,并不意味着它同样有效,甚至是适当的。
Another bad way of "fixing" the LazyInitializationException
is the Open Session in View, which is also an Anti-Pattern . “修复”
LazyInitializationException
另一种不好的方法是View中的Open Session,它也是Anti-Pattern 。
The best way to handle LazyInitializationException
is to JOIN FETCH
all one-to-one and many-to-one associations and up to a single one-to-many association. 处理
LazyInitializationException
的最佳方法是JOIN FETCH
所有一对一和多对一关联,以及单个单个多对关联。
If you need to fetch multiple one-to-many or many-to-many associations, then the first one should be JOIN FETCH-ed
, while the subsequent ones should be initialized with a separate query. 如果您需要获取多个一对多或多对多关联,则第一个关联应为
JOIN FETCH-ed
,而随后的关联应使用单独的查询初始化。 You can either navigate the association to trigger the initialization or use Hibernate#initialize
. 您可以导航关联以触发初始化,也可以使用
Hibernate#initialize
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.