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.

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;

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.

Group Id : com.roytuts
Artifact Id : hibernateproj
Version : auto-populated
Package : not required

Step 5. 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>hibernateproj</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>hibernateproj</name>
	<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>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>4.2.0.Final</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate.common</groupId>
			<artifactId>hibernate-commons-annotations</artifactId>
			<version>4.0.1.Final</version>
			<classifier>tests</classifier>
		</dependency>
		<dependency>
			<groupId>org.hibernate.javax.persistence</groupId>
			<artifactId>hibernate-jpa-2.0-api</artifactId>
			<version>1.0.1.Final</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>4.0.1.Final</version>
		</dependency>
		<dependency>
			<groupId>javax.validation</groupId>
			<artifactId>validation-api</artifactId>
			<version>1.0.0.GA</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.6.4</version>
		</dependency>
		<dependency>
			<groupId>org.jboss.logging</groupId>
			<artifactId>jboss-logging</artifactId>
			<version>3.1.0.CR2</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.6.4</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.10</version>
		</dependency>
		
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
</project>

Step 6. 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>

		<!-- database URL, database name - test -->
		<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
		<!-- database username -->
		<property name="connection.username">root</property>
		<!-- database password blank -->
		<property name="connection.password"></property>
		<!-- database driver -->
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<!-- database dialect -->
		<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
		<!-- show sql in the console -->
		<property name="show_sql">true</property>
		<!-- readable format for sql output in the console -->
		<property name="format_sql">true</property>
		<!-- session context is thread -->
		<property name="current_session_context_class">thread</property>
		<!-- mapping resource -->
		<mapping class="com.roytuts.hibernate.domain.Employee" />

	</session-factory>
</hibernate-configuration>

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

package com.roytuts.hibernate.domain;

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;
	}

}

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

package com.roytuts.hibernate.utils;

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();
	}

}

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

package com.roytuts.hibernate.test;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.roytuts.hibernate.domain.Employee;
import com.roytuts.hibernate.utils.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();
		} catch (Exception e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			if (session != null) {
				HibernateUtil.closeSession();
			}
		}

	}
}

Now check how evict() method works in Hibernate.

package com.roytuts.hibernate.test;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.roytuts.hibernate.domain.Employee;
import com.roytuts.hibernate.utils.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 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();
			}
		}

	}
}

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

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.

That’s all. Thank you for your reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

Leave a Reply

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