Entitymanager.flush() VS EntityManager.getTransaction().commit - What should I prefer?

Rox picture Rox · Jun 15, 2012 · Viewed 88.7k times · Source

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();
}

Answer

Nayan Wadekar picture Nayan Wadekar · Jun 15, 2012

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.