Came across this example at HIbernate commit() and flush()
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();
My understanding was hibernate synchronizes the DB session with hibernate when we do session.save(customer)
or session.update(....)
?
Does it sunchromized only at the time of commit/flush/refresh not at the time of update/save ?
The Hibernate Session
and the JPA EntityManager
(a.k.a Persistence Context) act as a write-behind cache so entity state transitions are staged and propagated to the DB during flush.
By default, the commit
call triggers a flush
and that's when INSERT, UPDATE, and DELETE statements are executed.
The benefits of the write-behind cache are the followings:
For more details about how Hibernate works, check out this tutorial which features over 100 articles about JPA, Hibernate, and the most common RDBMS.