The org.hibernate.Session interface is the most used interface in hibernate. It is used to perform the CURD operation. Following are the some commonly used methods of Session Interface.
Required:
- MySQL 5.1.6
- Java 8 (jdk 1.8)
- Hiberante 4.3.5
Dependencies, 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>hibernate4</groupId>
<artifactId>hibernate</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>hibernate</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.5.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
</dependencies>
</project>
Let’s create a table and entity class to examine each method in details.
Database Table
CREATE TABLE `orders` (
`orderNo` INT NOT NULL AUTO_INCREMENT ,
`orderBy` VARCHAR(45) NOT NULL ,
`orderDate` TIMESTAMP NOT NULL ,
`orderAmount` DECIMAL(16,2) NULL ,
PRIMARY KEY (`orderNo`) );
Entity class
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@Table(name="orders")
public class Orders implements Serializable{
private static final long serialVersionUID = -7290073664502187027L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer orderNo;
private String orderBy;
@Temporal(value = TemporalType.TIMESTAMP)
private Date orderDate;
private Double order amount;
public Orders() {
super();
}
public Orders(String orderBy, Date orderDate, Double orderAmount) {
super();
this.orderBy = orderBy;
this.orderDate = orderDate;
this.orderAmount = orderAmount;
}
public Integer getOrderNo() {
return orderNo;
}
public void setOrderNo(Integer orderNo) {
this.orderNo = orderNo;
}
public String getOrderBy() {
return orderBy;
}
public void setOrderBy(String orderBy) {
this.orderBy = orderBy;
}
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public Double getOrderAmount() {
return orderAmount;
}
public void setOrderAmount(Double orderAmount) {
this.orderAmount = orderAmount;
}
@Override
public String toString() {
return "Orders [orderNo=" + orderNo + ", orderBy=" + orderBy + ", orderDate=" + orderDate + ", orderAmount="
+ orderAmount + "]";
}
}
Create an XML file as “hibernate.cfg.xml” under src/main/resources as below.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/hibernate_dev</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping class="com.hibernate.entity.Orders"/>
</session-factory>
</hibernate-configuration>
Write a class HibernateUtil.java to create the SessionFactory instance.
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {
private static SessionFactory sessionFactory = null;
private static SessionFactory buildSessionFactory() {
try {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
} catch (Throwable ex) {
System.err.println("SessionFactory creation failed." + ex);
ex.printStackTrace();
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
if (sessionFactory == null)
sessionFactory = buildSessionFactory();
return sessionFactory;
}
}
save():
Syntax:
public Serializable save(Object object);
Persist the given transient instance, first assigning a generated identifier or using the current value of the identifier property if the assigned generator is used.
Let’s see the below code snippet to save a transient object into the database.
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.hibernate.entity.Orders;
import com.hibernate.util.HibernateUtil;
public class SessionInterfaceMethods {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Orders order = new Orders("Ram", new Date(), 1000.50);
Transaction t = session.beginTransaction();
session.save(order);
t.commit();
session.close();
}
}
when you run the above code it will insert a record into the database.
Hibernate: insert into orders (orderAmount, orderBy, orderDate) values (?, ?, ?)
We can retrieve the generated ID for the object using the save method. As shown in the save method syntax it returns Serializable.
Let’s modify the above code to retrieve the generated ID.
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.hibernate.entity.Orders;
import com.hibernate.util.HibernateUtil;
public class SessionInterfaceMethods {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Orders order = new Orders("kamal", new Date(), 1100.50);
Transaction t = session.beginTransaction();
Integer ID = (Integer) session.save(order);
System.out.println("generated id is : "+ID);
t.commit();
session.close();
}
}
The output of the above code snippet:

persist():
Syntax:
public void persist(Object object);
Make a transient instance persistent. As the syntax suggests it does not return any value.
Let’s see the below code snippet to persist a transient object into the database.
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.hibernate.entity.Orders;
import com.hibernate.util.HibernateUtil;
public class SessionInterfaceMethods {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Orders order = new Orders("anndy", new Date(), 500.00);
Transaction t = session.beginTransaction();
session.persist(order);
t.commit();
session.close();
}
}
when you run the above code it will insert a record into the database.
Hibernate: insert into orders (orderAmount, orderBy, orderDate) values (?, ?, ?)
load():
Syntax:
public Object load(Class theClass, Serializable id);
Return the persistent instance of the given entity class with the given identifier, assuming that the instance exists. This method might return a proxied instance that is initialized on-demand when a non-identifier method is accessed. As stated it is used to retrieve an object that you assume exists in the database if the object with the given identifier is not found it will throw “org.hibernate.ObjectNotFoundException”. So this method should not be used to determine whether an object exists or not.
Let’s see the below code snippet to load an object from the database for identifier 2.
import org.hibernate.Session;
import com.hibernate.entity.Orders;
import com.hibernate.util.HibernateUtil;
public class SessionInterfaceMethods {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Orders order = (Orders) session.load(Orders.class, 2);
System.out.println(order);
session.close();
}
}
When we run this code it will execute a select query and return an object of Orders if it exists or it will throw an Exception mention above.
Hibernate: select orders0_.orderNo as orderNo1_1_0_, orders0_.orderAmount as orderAmo2_1_0_, orders0_.orderBy as orderBy3_1_0_, orders0_.orderDate as orderDat4_1_0_ from orders orders0_ where orders0_.orderNo=?
Orders [orderNo=2, orderBy=kamal, orderDate=2018-11-10 13:51:31.0, orderAmount=1100.5]
get():
Syntax:
public Object get(Class clazz, Serializable id);
Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance. (If the instance is already associated with the session, return that instance. This method never returns an uninitialized instance.)
Let’s see the below code snippet to get an object from the database for identifier 1.
import org.hibernate.Session;
import com.hibernate.entity.Orders;
import com.hibernate.util.HibernateUtil;
public class SessionInterfaceMethods {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Orders order = (Orders) session.get(Orders.class, 1);
System.out.println(order);
session.close();
}
}
When we run this code it will execute a select query and return an object of Orders if it exists or null.
Hibernate: select orders0_.orderNo as orderNo1_1_0_, orders0_.orderAmount as orderAmo2_1_0_, orders0_.orderBy as orderBy3_1_0_, orders0_.orderDate as orderDat4_1_0_ from orders orders0_ where orders0_.orderNo=?
Orders [orderNo=1, orderBy=Ram, orderDate=2018-11-10 13:44:10.0, orderAmount=1000.5]
update():
Syntax:
public void update(Object object);
Update the persistent instance with the identifier of the given detached instance. If there is a persistent instance with the same identifier, an exception is thrown.
Let’s examine the below code snippet.
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.hibernate.entity.Orders;
import com.hibernate.util.HibernateUtil;
public class SessionInterfaceMethods {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Orders order = (Orders) session.get(Orders.class, 1);
System.out.println(order);
order.setOrderAmount(2345.00);
Transaction t = session.beginTransaction();
session.update(order);
t.commit();
System.out.println("order after update :" +order);
session.close();
}
}
when you run the above code it will first fetch an object of Orders from the database and then it will execute an update query to update the record with the changes made. See the output of the above code snippet.
Hibernate: select orders0_.orderNo as orderNo1_1_0_, orders0_.orderAmount as orderAmo2_1_0_, orders0_.orderBy as orderBy3_1_0_, orders0_.orderDate as orderDat4_1_0_ from orders orders0_ where orders0_.orderNo=?
Orders [orderNo=1, orderBy=Ram, orderDate=2018-11-10 14:41:33.0, orderAmount=1000.5]
Hibernate: update orders set orderAmount=?, orderBy=?, orderDate=? where orderNo=?
order after update :Orders [orderNo=1, orderBy=Ram, orderDate=2018-11-10 14:41:33.0, orderAmount=2345.0]
saveOrUpdate():
Syntax:
public void saveOrUpdate(Object object);
Either save or update the given instance, depending upon the resolution of the unsaved-value. A transient object will be saved or a detached instance containing a new or updated state will be updated.
Let’s examine the below code snippet.
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.hibernate.entity.Orders;
import com.hibernate.util.HibernateUtil;
public class SessionInterfaceMethods {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Orders order = new Orders("anna", new Date(), 1540.00);
Transaction t = session.beginTransaction();
session.saveOrUpdate(order);
t.commit();
System.out.println("order after insert:" +order);
session.close();
order.setOrderAmount(2000.25);
session = HibernateUtil.getSessionFactory().openSession();
t = session.beginTransaction();
session.saveOrUpdate(order);
t.commit();
session.close();
System.out.println("order after update :" +order);
}
}
When you run the above code it will insert a record into the database and later it will update the same instance with a new session. See the below output.
Hibernate: insert into orders (orderAmount, orderBy, orderDate) values (?, ?, ?)
order after insert:Orders [orderNo=5, orderBy=anna, orderDate=Sat Nov 10 14:52:55 IST 2018, orderAmount=1540.0]
Hibernate: update orders set orderAmount=?, orderBy=?, orderDate=? where orderNo=?
order after update :Orders [orderNo=5, orderBy=anna, orderDate=Sat Nov 10 14:52:55 IST 2018, orderAmount=2000.25]
merge():
Syntax:
public Object merge(Object object);
Copy the state of the given object onto the persistent object with the same identifier. If there is no persistent instance currently associated with the session, it will be loaded. Return the persistent instance. If the given instance is unsaved, save a copy of and return it as a newly persistent instance. The given instance does not become associated with the session.
Let’s examine the below code snippet.
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.hibernate.entity.Orders;
import com.hibernate.util.HibernateUtil;
public class SessionInterfaceMethods {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Orders order = new Orders("tina", new Date(), 1999.00);
Transaction t = session.beginTransaction();
session.save(order);
t.commit();
System.out.println("order after insert:" +order);
session.evict(order);
order.setOrderAmount(2999.00);
t = session.beginTransaction();
order = (Orders) session.merge(order);
t.commit();
session.close();
System.out.println("order after merge :" +order);
}
}
When you run the above code it will insert the order object. As we have called the evict method of the session, now if we call the merge method it will first load the persistent object from the database and then it will be updated. See the output of the above code snippet.
Hibernate: insert into orders (orderAmount, orderBy, orderDate) values (?, ?, ?)
order after insert:Orders [orderNo=7, orderBy=tina, orderDate=Sat Nov 10 15:20:32 IST 2018, orderAmount=1999.0]
Hibernate: select orders0_.orderNo as orderNo1_1_0_, orders0_.orderAmount as orderAmo2_1_0_, orders0_.orderBy as orderBy3_1_0_, orders0_.orderDate as orderDat4_1_0_ from orders orders0_ where orders0_.orderNo=?
Hibernate: update orders set orderAmount=?, orderBy=?, orderDate=? where orderNo=?
order after merge :Orders [orderNo=7, orderBy=tina, orderDate=Sat Nov 10 15:20:32 IST 2018, orderAmount=2999.0]
delete():
Syntax:
public void delete(Object object);
Remove a persistent instance from the database. The argument may be an instance associated with the receiving Session or a transient instance with an identifier associated with an existing persistent state.
Let’s examine the below code snippet.
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.hibernate.entity.Orders;
import com.hibernate.util.HibernateUtil;
public class SessionInterfaceMethods {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Orders order = new Orders("tina", new Date(), 1999.00);
order.setOrderNo(7); // assigning an existing order no this transient instance.
Transaction t = session.beginTransaction();
session.delete(order);
t.commit();
}
}
When you run the above code it will delete the record having ID as 7 from the database. See the output of the above code snippet.
Hibernate: delete from orders where orderNo=?
refresh():
Syntax:
public void refresh(Object object);
Re-read the state of the given instance from the underlying database.
Let’s examine the below code snippet.
import org.hibernate.Session;
import com.hibernate.entity.Orders;
import com.hibernate.util.HibernateUtil;
public class SessionInterfaceMethods {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Orders order = new Orders("bill", new Date(), 590.00);
System.out.println("intial order transient instance "+order);
session.save(order);
session.flush();
session.refresh(order);
System.out.println("order loaded from the database after refresh "+order);
}
}
When you run the above code it will fire an insert query on a transient object having any ID as null. When calling the refresh method on the same object we will get the ID. See the output of the above code snippet.
intial order transient instance Orders [orderNo=null, orderBy=bill, orderDate=Sat Nov 10 15:44:52 IST 2018, orderAmount=590.0]
Hibernate: insert into orders (orderAmount, orderBy, orderDate) values (?, ?, ?)
Hibernate: select orders0_.orderNo as orderNo1_1_0_, orders0_.orderAmount as orderAmo2_1_0_, orders0_.orderBy as orderBy3_1_0_, orders0_.orderDate as orderDat4_1_0_ from orders orders0_ where orders0_.orderNo=?
order loaded from the database after refresh Orders [orderNo=9, orderBy=bill, orderDate=2018-11-10 15:44:52.0, orderAmount=590.0]
flush():
Syntax:
public void flush() throws HibernateException;
Force this session to flush. Must be called at the end of a unit of work, before committing the transaction and closing the session. Flushing is the process of synchronizing the underlying persistent store with a persistent state held in memory.
Let’s examine the below code snippet.
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.hibernate.entity.Orders;
import com.hibernate.util.HibernateUtil;
public class SessionInterfaceMethods {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Orders order = new Orders("bill", new Date(), 590.00);
System.out.println("intial order transient instance "+order);
Transaction t = session.beginTransaction();
session.save(order);
session.flush();
t.commit();
session.close();
}
}
When you run the above code it will fire insert query when we call session.flush(). At this stage, the persistent object is synced with the database but the object is still to be persisted. The object will only persist when we commit the transaction. This method is useful when we require the ID of a persisting object before it is persisted into the database.
close():
Syntax:
public Connection close() throws HibernateException;
End the session by releasing the JDBC connection and cleaning up. It is not strictly necessary to close the session but you must at least disconnect it.
See the use of the close method in the above-used code snippet.
clear():
Syntax:
public void clear();
Completely clear the session. Evict all loaded instances and cancel all pending saves, updates, and deletions. Do not close open iterators or instances of ScrollableResults.
To use it just called session.clear();
session.clear();
cancelQuery():
Syntax:
public void cancelQuery() throws HibernateException;
Cancel the execution of the current query. This is the sole method of the session which may be safely called from another thread. throws HibernateException if there was a problem canceling the query.
evict():
Syntax:
public void evict(Object object);
Remove this instance from the session cache. Changes to the instance will not be synchronized with the database.
Let’s examine the below code snippet.
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.hibernate.entity.Orders;
import com.hibernate.util.HibernateUtil;
public class SessionInterfaceMethods {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Orders order = new Orders("lisa", new Date(), 2349.90);
Transaction t = session.beginTransaction();
session.save(order);
t.commit();
System.out.println("order after save is "+order);
session.evict(order);
System.out.println("order after sesion evict "+order);
t = session.beginTransaction();
session.save(order);
t.commit();
session.close();
}
}
When you run the above code it will persist an instance of Orders into the database. Once we call the session.evict() the instance of orders will we be considered as a new instance of orders if we call session.save() on it. See the output of the above code snippet.
Hibernate: insert into orders (orderAmount, orderBy, orderDate) values (?, ?, ?)
order after save is Orders [orderNo=12, orderBy=lisa, orderDate=Sat Nov 10 16:15:43 IST 2018, orderAmount=2349.9]
order after sesion evict Orders [orderNo=12, orderBy=lisa, orderDate=Sat Nov 10 16:15:43 IST 2018, orderAmount=2349.9]
Hibernate: insert into orders (orderAmount, orderBy, orderDate) values (?, ?, ?)
doWork():
Syntax:
public void doWork(Work work) throws HibernateException;
Controller for allowing users to perform JDBC related work using the Connection managed by this Session. As the syntax suggests return type as void it will not return any value. to return value use doReturningWork().
Let’s examine the below code snippet.
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.jdbc.Work;
import com.hibernate.util.HibernateUtil;
public class SessionInterfaceMethods {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction t = session.beginTransaction();
session.doWork(new Work() {
String query = "insert into orders (orderAmount, orderBy, orderDate) values (?, ?, ?)";
public void execute(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(query);
ps.setDouble(1, 3999.99);
ps.setString(2, "addy");
ps.setTimestamp(3, new Timestamp(new Date().getTime()));
int result = ps.executeUpdate();
System.out.println("result is "+result);
}
});
t.commit();
session.close();
}
}
When you run the above code it will insert a new record into the database with the given values.
result is 1
doReturningWork():
Syntax:
public T doReturningWork(ReturningWork work) throws HibernateException;
Controller for allowing users to perform JDBC related work using the Connection managed by this Session. After execution returns the result.
Let’s examine the below code snippet.
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.jdbc.ReturningWork;
import com.hibernate.util.HibernateUtil;
public class SessionInterfaceMethods {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction t = session.beginTransaction();
session.doReturningWork(new ReturningWork<Double>() {
public Double execute(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement("select orderAmount from orders where orderNo = 6");
ResultSet rs = ps.executeQuery();
rs.next();
Double orderAmount = rs.getDouble("orderAmount");
System.out.println("orderAmount "+orderAmount);
return orderAmount;
}
});
t.commit();
session.close();
}
}
When you run the above code it will print the output
orderAmount 1780.0
This is very useful when we have to call a stored procedure that returns some values.
That’s it in commonly used methods of session interface.
Read more about hibernate.
Reference https://docs.jboss.org/hibernate/orm/3.5/javadocs/org/hibernate/Session.html
HAPPY LEARNING !!