问题
I have an AuthenticationFilter that reads a token from the HTTP-Request, loads the user object from the database and sets it to the SecurityContextHolder:
SecurityContextHolder.getContext().setAuthentication(resultOfAuthentication);
Now in the request handler in a controller-class i want to access a field of the User-object the is lazily loaded. The problem is that I get a LazyInitializationException because the session is closed:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: a.b.c.User.devices, could not initialize proxy - no Session
Any ideas how I can keep the session open until the request is finished? So that I can lazily load fields of the User-Object?
回答1:
You would have to enclose that call inside your @Transactional method or to move the transaction boundaries higher up in the call hierarchy, so that invocation is included as well.
Other options would be to:
- Eagerly fetch all the required dependencies while the session is still opened (
join fetch) - Use
Hibernate.initialize(user.getAddresses());inside of the transactional context - Simply call size method on the depenedent colletions to initialze them
user.getAddresses().size:
来源:https://stackoverflow.com/questions/43010147/hibernate-session-is-closed-when-object-is-loaded-in-spring-request-filter