evict() method in Hibernate

The method evict() removes a single object from Session cache. So before you call evict() the object should be there in the Session cache. Therefore if you save the object first time, you have to save the object via Session.save(object). Subsequent update calls should follow through session.saveOrUpdate(object) or session.update(object) before calling evict() to remove the loaded object from the cache.

From http://docs.jboss.org/hibernate/core/3.3/reference/en/html/performance.html#performance-sessioncache

Whenever you pass an object to save(), update() or saveOrUpdate(), and whenever you retrieve an object using load(), get(), list(), iterate() or scroll(), that object is added to the internal cache of the Session.

When flush() is subsequently called, the state of that object will be synchronized with the database. If you do not want this synchronization to occur, or if you are processing a huge number of objects and need to manage memory efficiently, the evict() method can be used to remove the object and its collections from the first-level cache.

Here I will show you an example how an evict() method works in Hibernate.

Step 1. Create a MySQL table.

Step 2. Create a New Maven Project in Eclipse. Choose the Location for project. Click Next.

Step 3. Select Archetype as maven-archetype-quickstart from a list of Artifact Id. Click Next.

Step 4. In the next window, input Group Id, Artifact Id.

Step 5. Add dependencies for Hibernate in pom.xml file.

Step 6. Create hibernate.cfg.xml file with below source code.

Step 7. Create POJO file for Java class to database table mapping.

Step 8. Create HibernateUtils.java for creating singleton SessionFactory from which Session object will be created.

Step 9. Create a test class for saving some data to the database table.

Now check how evict() method works in Hibernate.

Step 10. Run the test class, you will see the below output.

The above output clearly shows that before calling evict() method the object persists in the first level cache, i.e., in Session object and when evict() method is called then the object from the first level session gets removed.

That’s all. Thank you for your reading.

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.