Spring Boot Data JPA自定义删除方法事务管理异常及配置疑问
JPA Repository事务行为异常排查
开发Service方法时遇到了异常的事务行为:
- JpaRepository通过方法名自动生成的删除方法不具备事务性
- 自定义删除方法必须添加
@Modifying和@Transactional注解才能生效
代码示例
public interface MyEntityRepository extends JpaRepository<MyEntity, Integer> { @Query(value = "DELETE FROM MyEntity e WHERE e.otherEntity.Id = ?1") @Modifying @Transactional void deleteAllByOtherEntityId(String requestNumber); void deleteAllByOtherEntity_Id(String requestNumber); }
事务行为差异
在标记@Transactional的Service方法中调用上述两个方法时,出现明显差异:
- 自定义删除方法会创建新事务,提交后不受全局事务回滚影响
- 自动生成的删除方法日志显示无需创建事务(非事务性),可以正常随全局事务回滚
No need to create transaction for [org.springframework.data.jpa.repository.support.SimpleJpaRepository.deleteAllByOtherEntity_Id]:
This method is not transactional.
目前自动生成的方法可以满足需求,但需要确认该行为是否为Spring Data JPA的预期表现,或是存在配置遗漏。
补充配置问题
后续发现配置存在异常:即使是只读JPA方法(如findById)也会创建独立事务,日志如下:
Creating new transaction with name [org.springframework.data.jpa.repository.support.SimpleJpaRepository.findById]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly
此前未发现该问题,是因为设置了:
enabledefaulttransactions=false
内容的提问来源于stack exchange,提问作者Martin Pichler
相关产品推荐
相关产品推荐

