【发布时间】:2017-01-09 01:31:40
【问题描述】:
我的 Spring 应用始终使用 @org.springframework.transaction.annotation.Transactional 来打开事务。为了减少与事务相关的不必要开销,我已开始在应用程序中不需要事务的区域中删除其中一些注释。
在此过程中,我注意到已删除 @Transactional 注释的 @Controller 类(在类级别或方法级别)仍然能够使用 SessionFactory#getCurrentSession()。但是,当我从@Service(特别是org.springframework.security.core.userdetails.UserDetailsService 的实现)中删除@Transactional 注释并尝试调用SessionFactory#getCurrentSession() 时,我收到以下信息:
Caused by: org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:134)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1014)
at com.xxx.datasource.AbstractDAO.getSession(AbstractDAO.java:35)
at com.xxx.datasource.UserDAO.getLoginUser(UserDAO.java:209)
at com.xxx.datasource.UserDAO.getLoginUser(UserDAO.java:199)
at com.xxx.spring.userdetails.service.UserDetailsServiceImpl.loadUserByUsername(UserDetailsServiceImpl.java:24)
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:102)
... 49 more
为什么会发生这种情况/是什么决定了SessionFactory#getCurrentSession() 是返回会话还是抛出异常?
(Spring 4.1.9 和 Hibernate 4.3.11)
【问题讨论】:
-
Spring 使用过滤器保持打开休眠会话以供 Web 使用。请参阅 [docs.spring.io/spring-framework/docs/2.5.6/api/org/… 。但是 thuis 仅适用于视图,并且在服务器端,您需要拥有自己的事务注释标记来根据需要管理事务。