Entitymanager.flush()VS EntityManager.getTransaction()。commit - 我应该更喜欢什么? [英] Entitymanager.flush() VS EntityManager.getTransaction().commit - What should I prefer?

查看:106
本文介绍了Entitymanager.flush()VS EntityManager.getTransaction()。commit - 我应该更喜欢什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新数据库时我应该更喜欢什么?什么是专业人士和使用哪种方法,何时使用其中一种?

What should I prefer when updating the database? What are the pros & cons with either method and when shall I use the one or the other?

public void disemployEmployee(Integer employeeId, Date endDate) {
    Employee employee = (Employee)em.find("Employee", employeeId);
    employee.getPeriod().setEndDate(endDate);
    em.flush();
}

public void disemployEmployee(Integer employeeId, Date endDate) {
    Employee employee = (Employee)em.find("Employee", employeeId);
    em.getTransaction().begin();
    employee.getPeriod().setEndDate(endDate);
    em.getTransaction().commit();
}


推荐答案

在你的第一个例子中,遇到flush后,数据的更改会反映在数据库中,但它仍处于事务中。

In your first example, the changes to the data are reflected in database after encountering flush, but it is still in transaction.

但在第二个示例中,您将立即提交事务。因此,对数据库和数据库进行了更改。交易也在那里结束。

But in second example, you are committing transaction immediately. Therefore the changes are made into the database & transaction also ends there.

有时,刷新可能有助于在正在进行的交易和交易之间保持数据。然后最后提交更改。因此,如果之后出现问题,您也可以回滚以前的更改,例如批量插入/更新。

Sometimes, flush may be useful to persist the data in between the ongoing transaction & then finally commit the changes afterwards. So you can also rollback the previous changes if there occurs some problem afterwards, like for batch insert/update.

这篇关于Entitymanager.flush()VS EntityManager.getTransaction()。commit - 我应该更喜欢什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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