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 Subsequent update calls should follow through session.saveOrUpdate(object) or session.update(object) before calling evict() to remove the loaded object from the cache.

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.


Hibernate 4.0.1.Final, Java 8, MySQL 5.6

Example with Source Code

Creating MySQL Table

Create a MySQL table. We will save or retrieve data from the below table through Hibernate API.

CREATE TABLE `employee` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `designation` varchar(50) NOT NULL,
  `joiningdate` varchar(20) NOT NULL,
  `phone` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)

Creating Project

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

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

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

Group Id: com.roytuts, Artifact Id: hibernate-evict

Updating pom.xml

Add dependencies for Hibernate in pom.xml file.

<project xmlns=""

Creating Hibernate Configuration

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

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "">
		<property name="connection.url">jdbc:mysql://localhost:3306/roytuts</property>
		<property name="connection.username">root</property>
		<property name="connection.password"></property>
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="">update</property>
		<property name="hibernate.current_session_context_class">thread</property>
		<property name="hibernate.query.factory_class">org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory</property>
		<property name="hibernate.show_sql">true</property>
		<property name="hibernate.format_sql">true</property>
		<mapping class="com.roytuts.hibernate.domain.model.Employee" />

Creating Domain Object

Create POJO file for Java class to database table mapping.

package com.roytuts.hibernate.domain.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
public class Employee {
	private Long id;
	private String name;
	private String designation;
	private String joiningdate;
	private String phone;
	public Employee() {
	public Employee(String name, String designation, String joiningdate, String phone) { = name;
		this.designation = designation;
		this.joiningdate = joiningdate; = phone;
	public Long getId() {
		return id;
	public void setId(Long id) { = id;
	public String getName() {
		return name;
	public void setName(String name) { = name;
	public String getDesignation() {
		return designation;
	public void setDesignation(String designation) {
		this.designation = designation;
	public String getJoiningdate() {
		return joiningdate;
	public void setJoiningdate(String joiningdate) {
		this.joiningdate = joiningdate;
	public String getPhone() {
		return phone;
	public void setPhone(String phone) { = phone;
	public String toString() {
		return "Employee ID: " + id + ", Name: " + name + ", Designation: " + designation + ", Joining Date: "
				+ joiningdate + ", Phone: " + phone;

Creating Hibernate SessionFactory

Create for creating singleton SessionFactory from which Session object will be created.

package com.roytuts.hibernate.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class HibernateUtil {
	private static ServiceRegistry serviceRegistry;
	private static SessionFactory sessionFactory;
	public static SessionFactory getSessionFactory() {
		try {
			Configuration configuration = new Configuration();
			serviceRegistry = (ServiceRegistry) new ServiceRegistryBuilder()
			sessionFactory = configuration.buildSessionFactory(serviceRegistry);
			// Create the SessionFactory from hibernate.cfg.xml
			return sessionFactory;
		} catch (Throwable ex) {
			// Make sure you log the exception, as it might be swallowed
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
	public static void closeSession() {
		// Close caches and connection pools

Creating Main Class

Create a main class for saving some data to the database table. We will test evict() method in this main class.

package com.roytuts.hibernate.test;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.roytuts.hibernate.domain.model.Employee;
import com.roytuts.hibernate.util.HibernateUtil;
public class EvictMethodTest {
	public static void main(String[] args) {
		Session session = null;
		Transaction transaction = null;
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			transaction = session.beginTransaction();
			Employee employee = new Employee();
			employee.setDesignation("Software Engineer");
			System.out.println("Employee saved: " + employee);
			Employee employee1 = (Employee) session.load(Employee.class, new Long(1));
			System.out.println("Before evict() session contains employee1 : " + session.contains(employee1));
			System.out.println("After evict() session contains employee1 : " + session.contains(employee1));
		} catch (Exception e) {
		} finally {
			if (session != null) {

Testing the Application

Now check how evict() method works in Hibernate by running the above main class. You will get below output in the console:

        (id, designation, joiningdate, name, phone)
        (null, ?, ?, ?, ?)
Employee saved: Employee ID: 1, Name: Soumitra, Designation: Software Engineer, Joining Date: 18-Dec-2013, Phone: 1234567890
Before evict() session contains employee1 : true
After evict() session contains employee1 : false

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.

Source Code

You can download source code.

That’s all. Thank you for your reading.

Leave a Reply

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