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(); }
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With