I referred many articles but still I still not clear on what session.clear
perform in hibernate.
According to what I came across so far is, When we use batch save / update as shown below:
Session session = SessionFactory.openSession(); Transaction tx = session.beginTransaction(); for ( int i=0; i<100000; i++ ) { Employee employee = new Employee(.....); session.save(employee); if( i % 50 == 0 ) { // Same as the JDBC batch size //flush a batch of inserts and release memory: session.flush(); session.clear(); } } tx.commit(); session.close();
sesion.flush();
is used in flushing the session forces Hibernate to synchronize the in-memory state of the Session with the database.
Question
1. After flushing the session, why is it necessary to do session.clear()
? Is it really required ?
2. Will session.clear()
perform commit action ?
3. If session.clear()
evicts all loaded objects, what happens internally while commit and rollback actions are performed ?
Think of the Session as a cache of entities you have already loaded from (or persisted to) the database since you've started the current transaction.
Session.clear
is not mandatory in any way, but is useful if you do a lot of entity loading/saving within one transaction, to avoid getting out of memory error. In your example, you'll have 50 employee
entities replicated in the session. Without the flush
and clear
method call every 50 save()
you would have had 100.000 entities replicated in the session (and not garbage collectable, because the session has a link to the entity).
Session.clear
will not perform commit nor rollback. Not even a flush
(hence why you should do flush before a Session.clear
, so that hibernate generates sql queries for pending entities updates.
Rollback or commit actions are not performed on the application side, but in the database : hibernate will just ask the database to commit or rollback (Hibernate might trigger a flush before the commit action, but the flush is not part of the commit). The commit action will not (and can't) access the session. It is an database internal mechanism that will persist (or revert) the data modification performed thanks to all SQL queries run since the start of the transaction.
Exactly in the same way, opening a transaction in hibernate is not performing a lot of things : mainly getting a db connection out of the pool, and telling the database to NOT auto_commit
following sql queries but to wait for a commit or rollback command.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With