解决报错:JPA No EntityManager with actual transaction available for current thread
作者:互联网
1.发生场景
报错发生的情况是这样,在service中,先调用了JPA的 deleteAllByxxx 方法,再调用JPA的 save 方法插入了新的数据。
报错信息如下:
"javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'remove' call at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:282) at com.sun.proxy.$Proxy91.remove(Unknown Source) at org.springframework.data.jpa.repository.query.JpaQueryExecution$DeleteExecution.doExecute(JpaQueryExecution.java:276) at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:87) at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:116) at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:106) at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:499) at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:477) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:56) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
......
2.解决方法
在对应的Service或组件上添加@Transactional,或者在JPA的 deleteAllByxxx 方法上添加也可以,根据具体业务场景来选择添加事务注解的位置。
ps:
1. flush()可手动地控制将实体类中的数据推到数据库,不知道好不好用,某些特殊场景可能用的上,记录一下
2. 不知道如果使用alibaba规范插件能不能检测出来
标签:available,EntityManager,java,repository,jpa,springframework,报错,org,data 来源: https://www.cnblogs.com/feng-gamer/p/14852918.html