Could not obtain transaction-synchronized Session for current thread异常解决办法

如题,使用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同样可以解决这个问题。

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

luffy5459

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值