Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate: flush() and commit()

Is it good practice to call org.hibernate.Session.flush() separately?

As said in org.hibernate.Session docs,

Must be called at the end of a unit of work, before commiting the transaction and closing the session (depending on flush-mode, Transaction.commit() calls this method).

Could you explain the purpose of calling flush() explicitely if org.hibernate.Transaction.commit() will do it already?

like image 915
bsiamionau Avatar asked Jan 29 '13 11:01

bsiamionau


People also ask

Is flush same as commit?

flush() is always called as part of a call to commit() (1). When you use a Session object to query the database, the query will return results both from the database and from the flushed parts of the uncommitted transaction it holds.

What is flush method in Hibernate?

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 is commit in Hibernate?

Commit will make the database commit. The changes to persistent object will be written to database. Flushing is the process of synchronizing the underlying persistent store with persistant state held in memory.

What is dirty check in Hibernate?

Hibernate provides as feature called Automatic Dirty checking whereby changes to a persistent object are automatically saved to the database when the session is flushed or the transaction is committed. So the code does not need to invoke an explicit save or update.


1 Answers

In the Hibernate Manual you can see this example

Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction();  for (int i = 0; i < 100000; i++) {     Customer customer = new Customer(...);     session.save(customer);     if (i % 20 == 0) { // 20, same as the JDBC batch size         // flush a batch of inserts and release memory:         session.flush();         session.clear();     } }  tx.commit(); session.close(); 

Without the call to the flush method, your first-level cache would throw an OutOfMemoryException

Also you can look at this post about flushing

like image 62
Aleksei Bulgak Avatar answered Oct 18 '22 02:10

Aleksei Bulgak