JPA:在同一事务中插入和删除对象 [英] JPA : insert and delete object in same transaction

查看:81
本文介绍了JPA:在同一事务中插入和删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在事务中将对象插入数据库,然后将该对象保存在数据库中,一旦完成特定操作,我想删除该对象.我可以再次重新启动事务并执行删除然后提交吗?这是正确的方法吗?

I want to insert an object into database in a transaction and after that object is saved in the database, I'd like to delete that it once a specific operation is done. Can I restart the transaction again and perform deletion and then commit? Is this a correct way of doing it?

示例:

Employee employee = new Employee();
String name = "Ronnie";
entityManager.getTransaction.begin();
employee.setName(name);
entityManager.persist(employee);
entityManager.getTransaction.commit();

//After few steps

entityManager.getTransaction.begin();
entityManager.remove(employee);
entityManager.getTransaction.commit();

推荐答案

简短回答:是的,您可以解决所有问题.

SHORT ANSWER: Yes, you can do that whithout problems.

长答案:是的,可以.
每个交易都独立于任何其他交易.因此,如果您执行一些操作,请提交它们(请记住,提交事务将执行数据库中的操作,然后将其关闭),然后再重新打开它,它与上一个事务无关.
您甚至可以通过将更改刷新到数据库来完成同一个事务,而无需关闭它:

LONG ANSWER: Yes, you can.
Every transaction is independent of any other transaction. So, if you do some operations, commit them (remember, committing a transaction execs the operations in the DB, and closes it), and then reopen it lately, it is independent of the last transaction.
You can even be in the same transaction, whithout closing it, by flushing changes to the DB:

Employee employee = new Employee();
String name = "Ronnie";
entityManager.getTransaction.begin();
employee.setName(name);
entityManager.persist(employee);
entityManager.flush();

//After few steps, the transaction is still the same
entityManager.remove(employee);
entityManager.getTransaction.commit();

这篇关于JPA:在同一事务中插入和删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆