Springbootjpa删除数据和事务管理的问题实例详解
今天我们介绍的是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 forcurrent 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 删除数据和事务管理的问题实例详解的介绍就到这⾥,希望对⼤家有所帮助,欢迎⼤家参阅本站其他专题。