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 bat
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.