clear(), evict() and close() methods in Hibernate

Posted on Updated on

HibernateClear () :  When this method get called inside transaction boundry then all objects which are currently associate with particular session will be  disconnected / clean or no longer associate with that Session instance.

Therefore, after calling this method nothing will be performed on persistance layer or DB.

evict():  Removes the object from the session. This method is used to dissociate/disconnect the specified object from the session.

Close() : Close session by calling session.close() method, means End the session and releasing the JDBC Connection and clean up.

 

Below, we demonstrated using examples through it would be easier to grab the terms difference.

Student.java :- This is a JPA Entity class.


package com.itexperts.hibernate.model;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
@Table(name = "Student")
public class Student {

	@Id
	@GeneratedValue
	private long id;
	@Column(name = "NAME")
	private String name;
	@Column(name = "ENROLL_NO")
	private String rollno;
	@Column(name = "EMAIL")
	private String email;

	@Column(name = "created_date")
	@Temporal(TemporalType.DATE)
	private Date enrollmentDate;

	public Student() {
	}

	public Student(String name, String rollno, String email) {
		super();
		this.name = name;
		this.rollno = rollno;
		this.email = email;
		this.enrollmentDate = new Date();
	}

	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 getRollno() {
		return rollno;
	}

	public void setRollno(String rollno) {
		this.rollno = rollno;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public Date getEnrollmentDate() {
		return enrollmentDate;
	}

	public void setEnrollmentDate(Date enrollmentDate) {
		this.enrollmentDate = enrollmentDate;
	}

}


Hibernate Configuration File under resource folder:-

Note: Here we set Hibernate config property( hbm2ddl.auto) is create which means every time when program get executed, Hibernate automatically drop scheme and recreate Entity Table.


<?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/mydb</property>
 <property name="connection.username">root</property>
 <property name="connection.password">root</property>
 <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
 <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
 
 <property name="show_sql">true</property>
 
 <!-- <property name="format_sql">true</property> -->
 <property name="hbm2ddl.auto">create</property>
 
 <!-- JDBC connection pool (use the built-in) -->
 <property name="connection.pool_size">1</property>
 <property name="current_session_context_class">thread</property>
 
<!-- <mapping class="com.itexperts.hibernate.model.Employee"/>
 <mapping class="com.itexperts.hibernate.model.Student"/>

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

In this below example, we will see how session.clear() work and  it’s implementation.

HibernateTest1.java:- Here we have two sessions, one for saving persistant object and right after open another session to get Object from DB using get().


package com.itexperts.relationship.example;

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

import com.itexperts.hibernate.model.Student;
import com.itexperts.utils.HibernateUtils;

public class HibernateTest1 {

	public static void main(String[] args) {
		
		// 3 Student Objects Initialized here.
		
		Student student0 = new Student("Student1", "Student1-234","Student1@domain.com");
		Student student1 = new Student("Student1", "Student1-234","Student1@domain.com");
		Student student2 = new Student("Student1", "Student1-234","Student1@domain.com");
		
		// This Transaction boundry, Transist Objects get persisted.
		// Start Session 1
		
		Session session = HibernateUtils.getInstance().openSession();
		Transaction tx =  session.beginTransaction();
		
		
		session.save(student0);
		session.save(student2);
		session.save(student1);
		
		tx.commit();
		session.close();
		// End Session1
		
		// Again after saving Student Objects, poll up these object in another Transaction scope.
		
		session = HibernateUtils.getInstance().openSession();
		tx =  session.beginTransaction();
		
		Student get_Student1 = (Student) session.get(Student.class, 1L);
		
		get_Student1.setName("Updated Student1");
		
		// Completely clear the session. Evict all loaded instances and cancel all pending saves, updates and deletions.
		// after this Statement, None of operation will be performed on DB.
		session.clear();
		// nothing reflected on Student1 instance in DB.
		
		tx.commit();
		session.close();
	}
}

Generated Output here: here no any update SQL command fired.

Hibernate: drop table if exists Student
Hibernate: create table Student (id bigint not null auto_increment, EMAIL varchar(255), created_date date, NAME varchar(255), ENROLL_NO varchar(255), primary key (id))
Hibernate: insert into Student (EMAIL, created_date, NAME, ENROLL_NO) values (?, ?, ?, ?)
Hibernate: insert into Student (EMAIL, created_date, NAME, ENROLL_NO) values (?, ?, ?, ?)
Hibernate: insert into Student (EMAIL, created_date, NAME, ENROLL_NO) values (?, ?, ?, ?)
Hibernate: select student0_.id as id0_0_, student0_.EMAIL as EMAIL0_0_, student0_.created_date as created3_0_0_, student0_.NAME as NAME0_0_, student0_.ENROLL_NO as ENROLL5_0_0_ from Student student0_ where student0_.id=?

Next, We will see how session.evit(object) work and it’s Implementation:-

Remove this instance from the session cache. Changes to the instance will not be synchronized with the database. This operation cascades to associated instances if the association is mapped with cascade="evict".


package com.itexperts.relationship.example;

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

import com.itexperts.hibernate.model.Student;
import com.itexperts.utils.HibernateUtils;

public class HibernateTest1 {

	public static void main(String[] args) {
		
		// 3 Student Objects Initialized here.
		
		Student student0 = new Student("Student1", "Student1-234","Student1@domain.com");
		Student student1 = new Student("Student1", "Student1-234","Student1@domain.com");
		Student student2 = new Student("Student1", "Student1-234","Student1@domain.com");
		
		// This Session boundry, Transist Object get persisted.
		// Start Session 1
		
		Session session = HibernateUtils.getInstance().openSession();
		Transaction tx =  session.beginTransaction();
		
		
		session.save(student0);
		session.save(student2);
		session.save(student1);
		
		tx.commit();
		session.close();
		
		
		// Again after saving Student Object, poll up these object again.
		
		session = HibernateUtils.getInstance().openSession();
		tx =  session.beginTransaction();
		
		Student get_Student1 = (Student) session.get(Student.class, 1L);
		Student get_Student2 = (Student) session.get(Student.class, 2L);
		
		get_Student1.setName("Updated Student1");
		get_Student1.setName("Updated Student2");
		
		// Remove this instance from the session cache. Changes to the instance
		// will not be synchronized with the database. This operation cascades
		// to associated instances if the association is mapped with
		// cascade="evict".
		session.evict(get_Student2);
		// get_Student2 Object no more exists in Session therefore updation will not happened
		
		get_Student1 = (Student) session.get(Student.class, 1L);
		get_Student2 = (Student) session.get(Student.class, 2L);
		
                // Again we check out updatation get reflected or not..
		System.out.println(" Student1 Name :"+get_Student1.getName());
		System.out.println(" Student2 Name :"+get_Student2.getName());
		
		tx.commit();
		session.close();

	}
}


Generated Output:- here only one update command is issued by Hibernate subsequently only one Object get reflected in Database. In below output, you can see only student1’s name value get reflected while student2’s name remain same.

Hibernate: drop table if exists Student
Hibernate: create table Student (id bigint not null auto_increment, EMAIL varchar(255), created_date date, NAME varchar(255), ENROLL_NO varchar(255), primary key (id))
Hibernate: insert into Student (EMAIL, created_date, NAME, ENROLL_NO) values (?, ?, ?, ?)
Hibernate: insert into Student (EMAIL, created_date, NAME, ENROLL_NO) values (?, ?, ?, ?)
Hibernate: insert into Student (EMAIL, created_date, NAME, ENROLL_NO) values (?, ?, ?, ?)
Hibernate: select student0_.id as id0_0_, student0_.EMAIL as EMAIL0_0_, student0_.created_date as created3_0_0_, student0_.NAME as NAME0_0_, student0_.ENROLL_NO as ENROLL5_0_0_ from Student student0_ where student0_.id=?
Hibernate: select student0_.id as id0_0_, student0_.EMAIL as EMAIL0_0_, student0_.created_date as created3_0_0_, student0_.NAME as NAME0_0_, student0_.ENROLL_NO as ENROLL5_0_0_ from Student student0_ where student0_.id=?
Hibernate: select student0_.id as id0_0_, student0_.EMAIL as EMAIL0_0_, student0_.created_date as created3_0_0_, student0_.NAME as NAME0_0_, student0_.ENROLL_NO as ENROLL5_0_0_ from Student student0_ where student0_.id=?
Student1 Name :Updated Student2
Student2 Name :Student1
Hibernate: update Student set EMAIL=?, created_date=?, NAME=?, ENROLL_NO=? where id=?

And Finally, session.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 disconnect it using session.disconnect()

Advertisements

One thought on “clear(), evict() and close() methods in Hibernate

    […] Student student0 = new Student("Student1", "Student1-234","Student1@domain.com"); Student student1 = new Student("Student1", "Student1-234","Student1@domain.com"); Student student2 = new Student("Student1", "Student1-234","Student1@domain.com"); Session session = HibernateUtils.getInstance().openSession(); Transaction tx = session.beginTransaction(); session.save(student0); session.save(student2); session.save(student1); Student get_student1 = (Student)session.get(Student.class, 1L); System.out.println(get_student1); tx.commit(); session.close(); […]

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s