I googled a lot and read about org.hibernate.Transaction.commit()
and org.hibernate.Session.flush()
a lot, know purpose of each method, but still have a question.
Is it good practice to call org.hibernate.Session.flush()
method by hand? 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 me purpose of callingorg.hibernate.Session.flush()
by hand iforg.hibernate.Transaction.commit()
will call it automatically?
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
One common case for explicitly flushing is when you create a new persistent entity and you want it to have an artificial primary key generated and assigned to it, so that you can use it later on in the same transaction. In that case calling flush would result in your entity being given an id.
Another case is if there are a lot of things in the 1st-level cache and you’d like to clear it out periodically (in order to reduce the amount of memory used by the cache) but you still want to commit the whole thing together.