Hibernate 5 - Remove an entity example

Posted on February 14, 2017


Technologies used:   JDK 1.8.0_121 | Hibernate 5.2.6.Final | Maven 3.3.9 | MySQL 5.7.12 | Eclipse Mars.2 (4.5.2)

In Hibernate, an entity can be removed from a database by calling the Session#delete()  or Session#remove(). Using these methods, we can remove a transient or persistent object from datastore.

The following examples demonstrate the use of Session#delete()  and  Session#remove() methods.

Project Structure

Review the following project structure.

Hibernate-delete-example.png

Demo Database

In this post, we will use the following CUSTOMER_TBL table.

mysql> select * from customer_tbl;
+---------+-------+
| CUST_ID | NAME  |
+---------+-------+
|       1 | Sunil |
|       2 | Joe   |
|       3 | Mike  |
|       4 | Sunil |
+---------+-------+

Jar dependencies

Add the following maven dependencies in pom.xml file.

  <dependencies>
    <!-- Mysql Connector -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>6.0.5</version>
    </dependency>
    <!-- Hibernate 5.2.6 Final -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>5.2.6.Final</version>
    </dependency>
  </dependencies>

Create an Entity class

Create a Customer entity class under com.boraji.tutorial.hibernate.entity package as follow.

Customer.java

package com.boraji.tutorial.hibernate.entity;

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

/**
 * @author imssbora
 */
@Entity
@Table(name = "CUSTOMER_TBL")
public class Customer {
   @Id
   @Column(name = "CUST_ID")
   private Long id;

   @Column(name = "NAME")
   private String name;

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

 

Create a Hibernate utility class

Create a helper class to bootstrap hibernate SessionFactory. Add  the Customer entity to MetadataSources for mapping.

HibernateUtil.java

package com.boraji.tutorial.hibernate;

import java.util.HashMap;
import java.util.Map;

import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

import com.boraji.tutorial.hibernate.entity.Customer;

/**
 * @author imssbora
 */
public class HibernateUtil {
   private static StandardServiceRegistry registry;
   private static SessionFactory sessionFactory;

   public static SessionFactory getSessionFactory() {
      if (sessionFactory == null) {
         try {
            StandardServiceRegistryBuilder registryBuilder = 
                  new StandardServiceRegistryBuilder();

            Map<String, String> settings = new HashMap<>();
            settings.put("hibernate.connection.driver_class", "com.mysql.cj.jdbc.Driver");
            settings.put("hibernate.connection.url", "jdbc:mysql://localhost:3306/BORAJI");
            settings.put("hibernate.connection.username", "root");
            settings.put("hibernate.connection.password", "admin");
            settings.put("hibernate.show_sql", "true");
            settings.put("hibernate.hbm2ddl.auto", "update");

            registryBuilder.applySettings(settings);
            registry = registryBuilder.build();
            MetadataSources sources = new MetadataSources(registry)
                  .addAnnotatedClass(Customer.class);

            sessionFactory = sources.buildMetadata().buildSessionFactory();

         } catch (Exception e) {
            System.out.println("SessionFactory creation failed");
            if (registry != null) {
               StandardServiceRegistryBuilder.destroy(registry);
            }
         }
      }
      return sessionFactory;
   }

   public static void shutdown() {
      if (registry != null) {
         StandardServiceRegistryBuilder.destroy(registry);
      }
   }
}

Removing an entity using delete() method

The following example deletes transient and persistent objects from datastore using Session#delete() method.

DeleteEntityExample.java

package com.boraji.tutorial.hibernate;

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

import com.boraji.tutorial.hibernate.entity.Customer;

/**
 * @author imssbora
 */
public class DeleteEntityExample {
   public static void main(String[] args) {
      Session session = null;
      Transaction transaction = null;
      try {
         session = HibernateUtil.getSessionFactory().openSession();
         transaction = session.getTransaction();
         transaction.begin();

         //Delete a persistent object
         Customer customer1=session.get(Customer.class, 1L);
         if(customer1!=null){
            session.remove(customer1);
            System.out.println("Customer 1 is deleted");
         }
         
         //Delete a transient  object
         Customer customer2=new Customer();
         customer2.setId(2L);
         session.remove(customer2);
         System.out.println("Customer 2 is deleted");
         
         transaction.commit();
      } catch (Exception e) {
         if (transaction != null) {
            transaction.rollback();
         }
         e.printStackTrace();
      } finally {
         if (session != null) {
            session.close();
         }
      }

      HibernateUtil.shutdown();
   }
}

Output

Hibernate: select customer0_.CUST_ID as CUST_ID1_0_0_, customer0_.NAME as NAME2_0_0_ from CUSTOMER_TBL customer0_ where customer0_.CUST_ID=?
Customer 1 is deleted
Hibernate: select customer_.CUST_ID, customer_.NAME as NAME2_0_ from CUSTOMER_TBL customer_ where customer_.CUST_ID=?
Customer 2 is deleted
Hibernate: delete from CUSTOMER_TBL where CUST_ID=?
Hibernate: delete from CUSTOMER_TBL where CUST_ID=?

 

Removing an entity using remove() method

The following example deletes transient and persistent objects from datastore using Session#remove() method.

RemoveEntityExample.java

package com.boraji.tutorial.hibernate;

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

import com.boraji.tutorial.hibernate.entity.Customer;

/**
 * @author imssbora
 */
public class RemoveEntityExample {
   public static void main(String[] args) {
      Session session = null;
      Transaction transaction = null;
      try {
         session = HibernateUtil.getSessionFactory().openSession();
         transaction = session.getTransaction();
         transaction.begin();

         //Remove a persistent object
         Customer customer1=session.get(Customer.class, 3L);
         if(customer1!=null){
            session.remove(customer1);
            System.out.println("Customer 3 is removed");
         }
         
         //Remove a transient  object
         Customer customer2=new Customer();
         customer2.setId(4L);
         session.remove(customer2);
         System.out.println("Customer 4 is removed");
         
         transaction.commit();
      } catch (Exception e) {
         if (transaction != null) {
            transaction.rollback();
         }
         e.printStackTrace();
      } finally {
         if (session != null) {
            session.close();
         }
      }

      HibernateUtil.shutdown();
   }
}

Output

Hibernate: select customer0_.CUST_ID as CUST_ID1_0_0_, customer0_.NAME as NAME2_0_0_ from CUSTOMER_TBL customer0_ where customer0_.CUST_ID=?
Customer 3 is removed
Hibernate: select customer_.CUST_ID, customer_.NAME as NAME2_0_ from CUSTOMER_TBL customer_ where customer_.CUST_ID=?
Customer 4 is removed
Hibernate: delete from CUSTOMER_TBL where CUST_ID=?
Hibernate: delete from CUSTOMER_TBL where CUST_ID=?
Download Sources