Hibernate: flush() and commit()

bsiamionau picture bsiamionau · Jan 29, 2013 · Viewed 156.9k times · Source

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?

Answer

Aleksei Bulgak picture Aleksei Bulgak · Jan 29, 2013

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