简体   繁体   中英

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

Once moved to Hibernate I got the famous exception " failed to lazily initialize a collection of role "

I found many solutions for this issue like these suggestions on this Question as well as the old OpenSessionInView method.

But these solutions are somehow outdated, and needs some changes on my running existing code that use eclipselink.

Is their a newer, modern, transparent solution that can save my time ?

Note : I am not using spring (only JPA and EJB) .

I think you are looking for the hibernate.enable_lazy_load_no_trans configuration property. 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.

Another bad way of "fixing" the LazyInitializationException is the Open Session in View, which is also an 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.

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. You can either navigate the association to trigger the initialization or use Hibernate#initialize .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM