How to Delete data in Hibernate

Create a simple Java Program to delete the database records using hibernate. well, we have already seen how to add data into the database, read data in hibernate and update data in hibernate. In this Hibernate tutorial, We will use the MYSQL database and see how to delete a database row into the MYSQL database using hibernate.

In hibernate to delete the database we just need to delete the data object. Other things will be taken care of by Hibernate only this is the beauty of Hibernate.

Delete data in Hibernate

Below are simple steps to delete data into the database using hibernate

  • Need a database to store the information
  • Add Hibernate dependency
  • Create a connection with the database using hibernate
  • Get the information and store the same information into the data object
  • Delete the object session.delete(user);
  • And Print the Object

Setup Database (MYSQL & MYSQL workbench)

Create Database name “hibernate_tutorial” in MYSQL and add some demo records in the table named “users”. Basic database operation is MYSQL workbench

Add Maven dependency for Hibernate

Create a maven project and add the below maven dependency into the pom.xml that will be in the root folder of your Java project. 

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

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.27</version>
</dependency>

Create hibernate configuration file (hibernate.cfg.xml)

Create an XML file and keep this file in the src folder also the name “hibernate.cfg.xml”. Name is not important to be the same but yes to In terms of development standards, will recommend keeping the same name.

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC
  "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory>
 
  <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
  <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_tutorial</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="hibernate.current_session_context_class">thread</property>
  
 </session-factory>
</hibernate-configuration>

Create Entity Class

Entity classes is a simple Java class where we will use some annotation that makes it entity class to map with a database table.

@Entity annotation is used to make the classes an entity.

@Table annotation is used to map the class with the database table name like @Table(name = “users”)

@Column annotation is used to map the column name with fields like @Column(name = “id”)

Users.java

package com.loginexample.entity;

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

@Entity
@Table(name = "users")
public class Users {

 @Id
 @Column(name = "id")
 private long id;
 
 @Column(name = "username")
 private String username;
 
 @Column(name = "password")
 private String password;
 
 @Column(name = "firstName")
 private String firstName;
 
 @Column(name = "lastName")
 private String lastName;
 

 public Users(String username, String password, String firstName, String lastName) {
  
  this.username = username;
  this.password = password;
  this.firstName = firstName;
  this.lastName = lastName;
 }

 public long getId() {
  return id;
 }

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

 public String getUsername() {
  return username;
 }

 public void setUsername(String username) {
  this.username = username;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }
 
 
 
}

Delete data into database using hibernate

Create a java main class (Main.java ) create an object of SessionFactory and configure the session

SessionFactory factory = new Configuration() .configure("hibernate.cfg.xml") .addAnnotatedClass(Users.class) .buildSessionFactory(); Session session = factory.getCurrentSession();

Create an object of Entity class(users), begin the transaction, get the record, delete the object data and Commit the transaction, and print response message.

package com.CbHibEample;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.sql.ordering.antlr.Factory;

import com.cbhibexample.entity.Users;


public class Main {
 public static void main(String[] args) {
  // TODO Auto-generated method stub

  SessionFactory factory = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Users.class)
    .buildSessionFactory();
  Session session = factory.getCurrentSession();
  try {
   session.beginTransaction();

   //Get Data in hibernate
   Users user = new Users();
   user =  (Users)session.get(Users.class, 4);
   
   //Delete Data in Hibernate
   session.delete(user);
   System.out.println(user);
   System.out.println("Data is Delete.................");
   
   session.getTransaction().commit();

  } finally {
   // TODO: handle finally clause
   //session.close();
   //factory.close();
  }
  
  
 
   
  
 }
}