Pages Navigation Menu

Coding is much easier than you think

Hibernate Delete Query example


 
In previous article we learnt to implement Hibernate Select Query example in Eclipse, In this article I will implement an example on delete the object from the database(Delete Query) using Hibernate.
 

Project Structure

 

 

Entity class

 

package entity;

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

@Entity
@Table(name = "STUDENT")
public class StudentEntity {

	@Id
	@Column(name = "ID")
	private int id;
	
	@Column(name = "NAME")
	private String name;
	
	@Column(name = "DEPARTMENT")
	private String department;
	
	@Column(name = "COLLEGE")
	private String college;

// Create Getters and Setters
}

 
Note: I have explained about every annotations used in the above file in the article Generic Hibernate Application Requirements
 

Hibernate Configuration file

 
Create a new XML file and give this new configuration file the default name hibernate.cfg.xmland place it src directory of your project.
 
File: hibernate.cfg.xml






	
	
                  oracle.jdbc.driver.OracleDriver
        
	system
	admin
	
                   jdbc:oracle:thin:@xxx.x.x.x:1521:XE
        

	
	org.hibernate.dialect.Oracle10gDialect

	
	true

	
	update
	
    



 

Hibernate Utility

 

package util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

import entity.StudentEntity;

public class HibernateUtil {

	public static void main(String[] args) {

		Configuration cf = new Configuration().configure("hibernate.cfg.xml");

		StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder();
		srb.applySettings(cf.getProperties());
		ServiceRegistry sr = srb.build();
		SessionFactory sf = cf.buildSessionFactory(sr);

		Session session = sf.openSession();
		StudentEntity std = (StudentEntity) session.load(StudentEntity.class, new Integer(2));
		Transaction tx = session.beginTransaction();
		session.delete(std);
		tx.commit();
		System.out.println("Object Deleted successfully !");
		session.close();
		sf.close();
	}
}

 
In the above program we are deleting an object, which is already persisted (inserted) in the database; So in order to delete an persisted object, we need to load that object from the database and pass that object to the delete() method of Session interface, now hibernate delete that object whenever the transaction is committed.
 
In the article Steps to be followed to use Hibernate in Java, I have explained the configuration/code used in above program in detail.
 

Data in DB before running the program

 

 

Run it – Eclipse Console

 

 

Data in DB after running the program