如题,使用hiernate5,在测试service层方法的时候报错,具体异常栈如下所示:
org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
at org.springframework.orm.hibernate5.SpringSessionContext.currentSession(SpringSessionContext.java:133)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:464)
at com.xxx.spring.hibernate.dao.impl.BaseDaoImpl.getSession(BaseDaoImpl.java:18)
at com.xxx.spring.hibernate.dao.impl.BaseDaoImpl.findById(BaseDaoImpl.java:33)
at com.xxx.spring.hibernate.service.AccountService.transfer(AccountService.java:14)
at com.xxx.spring.hibernate.service.AccountService$$FastClassBySpringCGLIB$$4cba99bb.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:738)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673)
at com.xxx.spring.hibernate.service.AccountService$$EnhancerBySpringCGLIB$$5ffd9fd2.transfer(<generated>)
at com.xxx.spring.hibernate.AccountTest.testTransfer(AccountTest.java:28)
通过检查,这是由于使用了事务管理,但是事务管理的切点没有包含service层的方法。
如图所示,将tx:advice中的注解打开,该问题就解决了。另外,如果开启了注解事务,配置文件中需要 这么配置:
<tx:annotation-driven transaction-manager="transactionManager"/>
在service类上,我们只需要通过加入注解@Transactional同样可以解决这个问题。