【问题标题】:Spring Data JPA Native SQL Query DELETE SQL QuerySpring Data JPA 原生 SQL 查询 DELETE SQL 查询
【发布时间】:2020-01-11 00:16:45
【问题描述】:

我使用@Modifying注解和@Query注解来执行SQL DELETE查询并从数据库表中删除记录。

@Modifying
@Query(value = "DELETE FROM CUSTOMERS  where CUSTOMERS.ID =:customersId and CUSTOMERS.USER_ID  = :userId and CUSTOMERS.USER_ID  = :sellerId", nativeQuery = true)
void deleteContributeur(@Param("customersId") Long customersId, @Param("userId") Long userId, @Param("sellerId") Long sellerId);

错误:

xxx.xxx.xx 中的异常原因 = 'javax.persistence.TransactionRequiredException:执行 更新/删除查询'和异常='执行更新/删除 询问;嵌套异常是 javax.persistence.TransactionRequiredException:执行一个 更新/删除查询'

【问题讨论】:

  • 这部分是否正确 "CUSTOMERS.USER_ID = :userId and CUSTOMERS.USER_ID = :sellerId""

标签: java sql spring spring-boot spring-data


【解决方案1】:

@Transactional注释服务方法。 你的查询是错误的。试试这个:

@Modifying
@Transactional
@Query(value = "DELETE FROM CUSTOMERS  where CUSTOMERS.ID =:customersId and CUSTOMERS.USER_ID  IN (:userId,:sellerId)", nativeQuery = true)
void deleteContributeur(@Param("customersId") Long customersId, @Param("userId") Long userId, @Param("sellerId") Long sellerId);

【讨论】:

    【解决方案2】:

    您需要一个事务来运行此查询。有很多方法,但最简单的一种是使用@Transactional 注释服务方法。但请记住它必须是 public 并从其他 bean 调用(包装在代理中)。

    【讨论】:

      【解决方案3】:

      方法具有默认可见性。因此代理机制没有激活!更改为公开后,一切都按预期工作!

      @Modifying
      @Transactional
      @Query(value = "DELETE FROM CUSTOMERS  where CUSTOMERS.ID =:customersId and CUSTOMERS.USER_ID  = :userId and CUSTOMERS.USER_ID  = :sellerId", nativeQuery = true)
      void deleteContributeur(@Param("customersId") Long customersId, @Param("userId") Long userId, @Param("sellerId") Long sellerId);
      

      我使用 Spring 包中的 @Transactional 注释,例如 @org.springframework.transaction.annotation.Transactional 然后它应该可以工作

      【讨论】:

        【解决方案4】:

        这是事务性问题 - 您需要添加 @Transactional。见this guide

        【讨论】:

          猜你喜欢
          • 2019-12-01
          • 1970-01-01
          • 2017-05-13
          • 2019-03-10
          • 2020-02-15
          • 2021-02-13
          • 2017-12-13
          • 2016-09-30
          • 1970-01-01
          相关资源
          最近更新 更多