JPA删除数据出现的一系列错误解决。

今天下午使用JPA删除数据时出现了Can not issue data manipulation statements with executeQuery() 后来又出现了TransactionRequiredException: Executing an update/delete query。那我们应该怎么解决这个问题呢?还有TransactionRequiredException: No EntityManager with actual transaction available for current thread错误。

我一开始的删除代码是这样的

  1. @Query(nativeQuery = true, value = "DELETE FROM sys_role_resource WHERE role_id = ?1")
  2. void deleteRrByRoleId(long roleId);

执行的过程中出现了Can not issue data manipulation statements with executeQuery(),后来发现我们是用删除功能的不是查询的,所以我们要添加@Modifying

  1. @Modifying
  2. @Query(nativeQuery = true, value = "DELETE FROM sys_role_resource WHERE role_id = ?1")
  3. void deleteRrByRoleId(long roleId);

再经过执行后结果还不是正确的,出现了TransactionRequiredException: Executing an update/delete query,就是说要添加事务的注解 @Transactional

  1. @Transactional
  2. @Modifying
  3. @Query(nativeQuery = true, value = "DELETE FROM sys_role_resource WHERE role_id = ?1")
  4. void deleteRrByRoleId(long roleId);

当然如果你不是用自定义的删除语句,就是说你没有@Query,而是默认的,我们就不用 @Modifying,但是也要@Transactional

  1. @Transactional
  2. void deleteByPk_RoleId(Long roleId);

如果没有添加@Transactional,会出现TransactionRequiredException: No EntityManager with actual transaction available for current thread 的错误

上面2个的@Transactional有什么区别呢:

  1. @Transactional
  2. @Modifying
  3. @Query(nativeQuery = true, value = DELETE FROM sys_role_resource WHERE role_id = ?1”)
  4. void deleteRrByRoleId(long roleId);
  5. @Transactional
  6. void deleteByPk_RoleId(Long roleId);

有什么区别,上面的会直接执行delete语句
下面的会先执行select 再执行delete