我想在事务中将对象插入数据库,然后将该对象保存在数据库中,一旦完成特定操作,我想删除该对象.我可以再次重新启动事务并执行删除然后提交吗?这是正确的方法吗?
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.getTransactionmit(); //After few steps entityManager.getTransaction.begin(); entityManager.remove(employee); entityManager.getTransactionmit();推荐答案
简短回答:是的,您可以解决所有问题.
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.getTransactionmit();更多推荐
JPA:在同一事务中插入和删除对象
发布评论