Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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(); } 
like image 854
Rox Avatar asked Jun 15 '12 09:06

Rox


People also ask

Does EntityManager flush commit?

The EntityManager. flush() operation can be used to write all changes to the database before the transaction is committed. By default JPA does not normally write changes to the database until the transaction is committed.

What is flush in EntityManager?

Flushing is the process of synchronizing the state of the persistence context with the underlying database. The EntityManager and the Hibernate Session expose a set of methods, through which the application developer can change the persistent state of an entity.

What does flush do in JPA?

Some confusing explanation: flush(); Flushing is the process of synchronizing the underlying persistent store with persistable state held in memory.it will update or insert into your tables in the running transaction, but it may not commit those changes.


1 Answers

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.

like image 147
Nayan Wadekar Avatar answered Sep 20 '22 13:09

Nayan Wadekar