In Spring with jpa/hibernate, how do I keep a session open to avoid lazy initialization exceptions?

HappyEngineer picture HappyEngineer · Jul 16, 2009 · Viewed 23.7k times · Source

I currently mark collections in entity beans as eager to avoid getting a lazy initialization exception when I try to access the collection properties after loading the bean with the EntityManager.

If I instead leave the collection as lazy loading, how do I keep a session open? I thought about trying @Transactional, but even if that worked I wouldn't want to do it because it doesn't seem right to leave a transaction open over a long method.

Answer

lucas picture lucas · Jul 16, 2009

https://www.hibernate.org/43.html

Basically, you have a few options.

-You can use the "open session in view" pattern where you use a filter/interceptor/AOP - style logic to open a session when server side logic begins, and close it when it's through.

-You could implement conversations spanning several request-response cycles.

A plain old Servlet Filter is the easiest.