Introduction

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.

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.

Prerequisites

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`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

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="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.roytuts</groupId>
	<artifactId>hibernate-evict</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
	<url>http://maven.apache.org</url>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>4.0.1.Final</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.10</version>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

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" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<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="hibernate.hbm2ddl.auto">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" />
	</session-factory>
</hibernate-configuration>

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;
@Entity
@Table
public class Employee {
	@Id
	@GeneratedValue
	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) {
		this.name = name;
		this.designation = designation;
		this.joiningdate = joiningdate;
		this.phone = phone;
	}
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.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) {
		this.phone = phone;
	}
	@Override
	public String toString() {
		return "Employee ID: " + id + ", Name: " + name + ", Designation: " + designation + ", Joining Date: "
				+ joiningdate + ", Phone: " + phone;
	}
}

Creating Hibernate SessionFactory

Create HibernateUtils.java 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();
			configuration.configure();
			serviceRegistry = (ServiceRegistry) new ServiceRegistryBuilder()
					.applySettings(configuration.getProperties()).buildServiceRegistry();
			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
		getSessionFactory().close();
	}
}

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.setName("Soumitra");
			employee.setDesignation("Software Engineer");
			employee.setJoiningdate("18-Dec-2013");
			employee.setPhone("1234567890");
			session.save(employee);
			transaction.commit();
			System.out.println("Employee saved: " + employee);
			System.out.println();
			Employee employee1 = (Employee) session.load(Employee.class, new Long(1));
			System.out.println("Before evict() session contains employee1 : " + session.contains(employee1));
			session.evict(employee1);
			System.out.println("After evict() session contains employee1 : " + session.contains(employee1));
		} catch (Exception e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			if (session != null) {
				HibernateUtil.closeSession();
			}
		}
	}
}

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:

Hibernate:
    insert
    into
        Employee
        (id, designation, joiningdate, name, phone)
    values
        (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 *