我的Spring应用程序始终使用@org.springframework.transaction.annotation.Transactional
来打开事务。为了减少与交易有关的不必要的开销,我已经开始删除不需要交易的应用领域中的一些注释。什么决定在@Transactional之外是否有休眠会话
这样做,我注意到@Controller
类已删除@Transactional
注释(在类级别或方法级别)仍然能够使用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()
将返回一个会话或抛出异常?
(春季4.1.9和4.3.11休眠)
Spring通过使用过滤器保持打开供网站使用的hibernate会话。请参阅[http://docs.spring.io/spring-framework/docs/2.5.6/api/org/springframework/orm/hibernate3/support/OpenSessionInViewFilter.html]。但是这只适用于视图,而在服务器端,您需要拥有自己的事务注释标记来根据需要管理事务。 –