jpa删除数据后数据库无修改_Spring boot jpa 删除数据和事务管理的问题实例详解...

本文详细探讨了Spring Boot JPA在删除数据时遇到的事务管理问题,包括不同层级添加@Transactional注解对删除操作的影响。实验表明,只有在Service层添加事务管理才能确保数据正确删除,而在Repository层的修改操作需要事务支持以保持数据完整性。同时,@Modifying和@Query配合使用可以避免先查询再删除的步骤。
摘要由CSDN通过智能技术生成

今天我们介绍的是jpa删除和事务的一些坑,接下来看看具体内容。

业务场景(这是一个在线考试系统)和代码:根据问题的id删除答案

repository层:

int deleteByQuestionId(Integer questionId);

service 层:

public void deleteChoiceAnswerByQuestionId(Integer questionId) {

choiceAnswerRepository.deleteByQuestionId(questionId);

测试层:

@Test

public void testDeleteByQuestionId() {

choiceAnswerService.deleteChoiceAnswerByQuestionId(5);

System.out.println("hehehhe");

System.out.println("hehehhe");

System.out.println("hehehhe");

System.out.println("hehehhe");

System.out.println("hehehhe");

System.out.println("hehehhe");

System.out.println("hehehhe");

}

问题1:如果各层都不加事务管理的话

@Transactional

会报这个错误

org.springframework.dao.InvalidDataAccessApiUsageException: No EntityManager with actual transaction available for current thread - cannot reliably process ‘remove' call; nested exception is javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process ‘remove' call

当我们除了query外的modiy和delete外如果没有各层的方法中进行事务管理的话也就是没加@Transactional话会报错

问题2:只在test层加@Transactional

没有错误但是数据并没有被删除,在用IDEA的调试是,在执行这个测试方法的过程时还可以在choiceanswer表中进行操作并没有加锁事务并没有起作用

问题3:只在 Repository层加@Transactional

public void deleteChoiceAnswerByQuestionId(Integer questionId) {

choiceAnswerRepository.deleteByQuestionId(questionId);

System.out.println(“hehehhe”);

System.out.println("hehehhe");

// questionRepository.delete(5);

System.out.println(“hehehhe”);

System.out.println("hehehhe");

System.out.println("hehehhe");

System.out.println("hehehhe");

System.out.println("hehehhe");

}

这时当执行完

choiceAnswerRepository.deleteByQuestionId(questionId);

数据里面被修改

问题4:只在 service层加@Transactional

当只有执行完service内的对应方法时数据才会被删除

问题5:在service 层和Repository都加上@transactional

当只有执行完service内的对应方法时数据才会被删除

问题6:只要在test(或者是除了service层和Repository层)加上@Transactional,不管service层和Repository层加不加@Transactional数据都不会被删除

问题7:

@Modifying

@Query(“delete from ChoiceAnswer c where c.question.id=?1 “)

@Transactional

int deleteByQuestionId(Integer questionId);

@Transactional

int deleteByQuestionId(Integer questionId);

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

下面的会先执行select 再执行delete

总结:

事务管理只有在service加上事务管理才起作用,query不需要事务管理但是delete update但需要事务管理为了不在Service层不加事务管理可以再Repository层的delete uodate加上@transactional 但这样不能真正保持事务的完整性.

本文关于Spring boot jpa 删除数据和事务管理的问题实例详解的介绍就到这里,希望对大家有所帮助,欢迎大家参阅本站其他专题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值