clear(), evict() and close() methods in Hibernate

clear():  Completely clear the session and is used to dissociate/disconnect all the objects from the session.

Example on clear()

Database table before execution


Database table after execution

  •  After calling session.clear(), emp1 and emp2 objects are disconnected from the session object. i.e emp1 and emp2 objects are moved from persistent state to detached state.
  • The table is not updated even though transaction is committed becuase emp1 and emp2 are in non-transaction state.

evict():  Removes the object from the session. This method is used to dissociate/disconnect the specified object from the session

 Example on evict()

Database table before execution


Database table after execution

Output in Eclipse

emp1 is not updated becuase we have called session.evict(emp1) and emp2 is updated.


close the session by calling session.close() after transaction is completed.All the associated objects will be dissociated after calling session.close().It is not  strictly necessary to close the session but you must at least using disconnct it using session.disconnect()




Posted in hibernate and tagged , , , , .

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.