今天下午使用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错误。
我一开始的删除代码是这样的
@Query(nativeQuery = true, value = "DELETE FROM sys_role_resource WHERE role_id = ?1")
void deleteRrByRoleId(long roleId);
执行的过程中出现了Can not issue data manipulation statements with executeQuery(),后来发现我们是用删除功能的不是查询的,所以我们要添加@Modifying
@Modifying
@Query(nativeQuery = true, value = "DELETE FROM sys_role_resource WHERE role_id = ?1")
void deleteRrByRoleId(long roleId);
再经过执行后结果还不是正确的,出现了TransactionRequiredException: Executing an update/delete query,就是说要添加事务的注解 @Transactional
@Transactional
@Modifying
@Query(nativeQuery = true, value = "DELETE FROM sys_role_resource WHERE role_id = ?1")
void deleteRrByRoleId(long roleId);
当然如果你不是用自定义的删除语句,就是说你没有@Query,而是默认的,我们就不用 @Modifying,但是也要@Transactional
@Transactional
void deleteByPk_RoleId(Long roleId);
如果没有添加@Transactional,会出现TransactionRequiredException: No EntityManager with actual transaction available for current thread 的错误
上面2个的@Transactional有什么区别呢:
@Transactional
@Modifying
@Query(nativeQuery = true, value = “DELETE FROM sys_role_resource WHERE role_id = ?1”)
void deleteRrByRoleId(long roleId);
与
@Transactional
void deleteByPk_RoleId(Long roleId);
有什么区别,上面的会直接执行delete语句
下面的会先执行select 再执行delete
原创来源:滴一盘技术