当前位置: 移动技术网 > IT编程>开发语言>Java > Spring boot jpa 删除数据和事务管理的问题实例详解

Spring boot jpa 删除数据和事务管理的问题实例详解

2019年07月19日  | 移动技术网IT编程  | 我要评论

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网