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(): 

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 *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">