Search code examples
javahibernateormtransactionshibernate-session

Does the Hibernate Session save operation synchronize with the underlying DB transaction?


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 ?


Solution

  • 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:

    • it's much easier to apply automatic JDBC batch updates
    • if there is no prior SELECT statement, the connection acquisition can be delayed until the flush, therefore reducing the database connection lease time.

    For more details about how Hibernate works, check out this tutorial which features over 100 articles about JPA, Hibernate, and the most common RDBMS.