SpringBoot—JPA: javax.persistence.TransactionRequiredException

问题

void deleteBy(int id);

  jpa调用deleteBy或者update时,抛异常Executing an update/delete query; nested exception is javax.persistence.TransactionRequiredException

解决方案

分析

  1. 因为事务问题,update、delete操作涉及到事务机制,需要进行设置。
  2. Spring Data JPA中的deleteByXXX,是先select查询,然后在整个Transaction完毕后,才执行delete。

方案1

    @Transactional
    @Modifying(clearAutomatically = true)
    @Query(value = "DELETE FROM `tb_a` WHERE `id` = ?1", nativeQuery = true)
    void deleteTb01ById(int id);

方案2

TbA removeById(int id);

方案3

void deleteBy(int id);

tbADao.deleteById(123);
tbADao.flush();

总结

  方案2和方案3供参考,本人常用方案1中的@Transactional、@Modifying配合@Query注解进行解决JPA deleteBy这个问题。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容