Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 387
HappyEngineer Avatar asked Jul 16 '09 20:07

HappyEngineer


1 Answers

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.

like image 84
lucas Avatar answered Sep 24 '22 22:09

lucas