Hibernate Session.delete() Example

In this tutorial we will use the Session.Delete() method to create an example in Hibernate for deleting an entity.

Hibernate Session.delete() Example

Hibernate Session.delete() Example - Write Hibernate program for deleting an entity

The Session object is the main interface between your Java program and the database. It provides the methods for deleting the data from database with the help of delete() method.

We are using the Eclipse IDE for this project you can download the source code of the project and run the example in the Eclipse IDE very easily. It contains all the required libraries of Hibernate 4.2.8.

About Hibernate Session.delete() method

This method is used to delete the entity instance from the persistence store (Database) and this change is permanent and you can't retrieve the deleted entity again once transaction is committed.

Method signature:

delete(Object object)

This method is taking the object (entity) as a parameter. The return type of this method is void. It generates the sql statement for delete and execute against the database. Here is an example of generated query:

delete from employee where id=?

Example code of session.delete() operation:

package net.roseindia;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import net.roseindia.model.*;
/**
 * @author Deepak Kumar 
 * Web: http://www.roseindia.net
 */

public class SessionDeleteExample {
	public static void main(String[] args) throws Exception {

		SessionFactory sessFact = HibernateUtil.getSessionFactory();
		Session session = sessFact.getCurrentSession();
		org.hibernate.Transaction tr = session.beginTransaction();
		Employee emp = (Employee)session.load(Employee.class, 2);
		System.out.println(emp.getId());
		System.out.println(emp.getEmpName());
		System.out.println(emp.getEmpMobileNos());
		//Delete the object
		session.delete(emp);
		
		tr.commit();
		System.out.println("Data Updated");
		sessFact.close();
	}
}

The above code first loads the entity using the following method:

Employee emp = (Employee)session.load(Employee.class, 2);

Then following code is used to delete the entity:

//Delete the object
session.delete(emp);

Here is the screen shot of the eclipse project:

Hibernate Session.delete() Example

If you run the code following output will be displayed:

Hibernate Session.delete() Example Output

Here is the code of the model class used in the example:

package net.roseindia.model;
import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import javax.persistence.Table;
/**
 * @author Deepak Kumar
 * Web: http://www.roseindia.net
 */
@Entity
@Table(name = "employee")
public class Employee implements Serializable{

	@Id
	@GeneratedValue
	@Column(name="id")
	private int id;	

	@Column(name="emp_name")
	private String empName;

	@Column(name="emp_address")
	private String empAddress;	  

	@Column(name="emp_mobile_nos")
	private String empMobileNos;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getEmpName() {
		return empName;
	}

	public void setEmpName(String empName) {
		this.empName = empName;
	}

	public String getEmpAddress() {
		return empAddress;
	}

	public void setEmpAddress(String empAddress) {
		this.empAddress = empAddress;
	}

	public String getEmpMobileNos() {
		return empMobileNos;
	}

	public void setEmpMobileNos(String empMobileNos) {
		this.empMobileNos = empMobileNos;
	}

}

The code of hibernate.cfg.xml file used in the project:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/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:3306/hibernate4</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>

<mapping class="net.roseindia.model.Employee" />

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

Here is the code of utility class which contains a method to get the SessionFactory:

package net.roseindia;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

/**
 * @author Deepak Kumar 
 * Web: http://www.roseindia.net
 */
public class HibernateUtil {
	private static final SessionFactory sessionFactory;

	private static ServiceRegistry serviceRegistry;

	static {

		try {

			Configuration configuration = new Configuration();
			configuration.configure();
			serviceRegistry = new ServiceRegistryBuilder().applySettings(
					configuration.getProperties()).buildServiceRegistry();
			sessionFactory = configuration.buildSessionFactory(serviceRegistry);

		} catch (Throwable th) {

			System.err.println("Enitial SessionFactory creation failed" + th);

			throw new ExceptionInInitializerError(th);

		}

	}

	public static SessionFactory getSessionFactory() {

		return sessionFactory;

	}
}

In this section you have learned how to delete the entity using Session.delete() method.

Download the Source code of the project discussed here.

Check more Hibernate 4.2 tutorials.