zoukankan      html  css  js  c++  java
  • 解决报错: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规范插件能不能检测出来

     
  • 相关阅读:
    Java集合概述
    Java8内存结构—永久代(PermGen)和元空间(Metaspace)
    ArrayList分析
    “三次握手,四次挥手”你真的懂吗?
    Object中的方法以及对象相等的判定
    笔记
    Mybatis中的@Param注解
    react与jQuery对比,有空的时候再翻译一下
    队列理论和队列网络模型 queueing theory and queueing network model
    下拉列表autocomplete各种实现方式比较
  • 原文地址:https://www.cnblogs.com/feng-gamer/p/14852918.html
Copyright © 2011-2022 走看看