Hibernate session is closed when object is loaded in Spring Request Filter

血红的双手。 提交于 2021-01-28 07:19:09

问题


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

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