Help needed with Spring/Hibernate Lazy-loading

旧巷老猫 提交于 2019-12-04 15:17:06

the problem is that HibernateInterceptor closes the session after returning from ProductService getProduct()

From the API DOCs:

This interceptor binds a new Hibernate Session to the thread before a method call, closing and removing it afterwards in case of any method outcome. If there already is a pre-bound Session (e.g. from HibernateTransactionManager, or from a surrounding Hibernate-intercepted method), the interceptor simply participates in it.

and opens a new one for the follwing call to ProductService.getProductName(). The newly created session has no knowledge of the Product Entity which you fetched from the DB in the previous session.

you have various possibilities to resolve this:

1.) add a method which eagerly loads the names, and use it in the specific contexts, this is obviuos ;)

2.) you can reattach the entity to the active session using Session.update(myProductEntity) before calling Product.getName() in ProductService.getProductName()

3.) you can wrap it all in a transaction which the wrapped method calls to ProductService.getProduct() and ProductService.getProductName() participate in. See Transaction Propagation

4.) in a web application you can use an OpenSessionInViewFilter to keep the session open as long as the view gets created in your controllers

5.) i think you can also use AOP directly. you can have an aspect keep the session open on an arbitrary Joinpoint but i have no real experience there and can not be more specific ;)

hope that helped...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!