Single logo
  • Courses
  • Articles
  • About
Join for freeJoin free
  1. Blog
  2. /
  3. S01L11 - Hibernate CURD operation - Delete

Hibernate Articles
0 views

S01L11 - Hibernate CURD operation - Delete


May 14, 2025

Hibernate CRUD Operations: Deleting Records with Ease

Table of Contents

  1. Introduction ........................................... 1
  2. Understanding CRUD Operations ..... 3
  3. Setting Up Hibernate for Deletion .. 5
  4. Implementing the Delete Operation .. 7
    • Code Walkthrough ............................ 8
  5. Running the Application ............... 12
  6. Best Practices for Deleting Records .. 15
  7. Conclusion ............................................ 18

Introduction

Welcome to the comprehensive guide on performing delete operations using Hibernate in Java applications. As part of the Hibernate CRUD (Create, Read, Update, Delete) operations, the delete functionality is crucial for managing your application's data effectively. This eBook will walk you through the steps required to delete records from your database seamlessly using Hibernate. Whether you're a beginner or a developer with basic knowledge, this guide is tailored to help you master the deletion process with clarity and precision.


Understanding CRUD Operations

Before diving into the deletion process, it's essential to understand the broader context of CRUD operations within Hibernate.

What is CRUD?

CRUD stands for Create, Read, Update, and Delete—the four basic functions of persistent storage. Hibernate, as an Object-Relational Mapping (ORM) tool, facilitates these operations by allowing developers to interact with the database using Java objects.

Operation Description Hibernate Method
Create Insert new records session.save()
Read Retrieve existing records session.get()
Update Modify existing records session.update()
Delete Remove records session.delete()

Importance of Delete Operation

The delete operation is fundamental for maintaining data integrity and ensuring that obsolete or unnecessary records do not clutter your database. Proper implementation ensures that deletions are handled efficiently and safely, preventing unintended data loss.


Setting Up Hibernate for Deletion

Before implementing the delete operation, ensure that your Hibernate setup is correctly configured.

Prerequisites

  • Java Development Kit (JDK) installed
  • Hibernate libraries added to your project
  • Database (e.g., MySQL, PostgreSQL) configured
  • Entity Classes defined (e.g., Users.java)
  • Hibernate Configuration File (hibernate.cfg.xml) set up

Project Structure

HibernateCRUD/
├── src/
│   └── main/
│       ├── java/
│       │   └── org/
│       │       └── studyeasy/
│       │           ├── App.java
│       │           └── entity/
│       │               └── Users.java
│       └── resources/
│           └── hibernate.cfg.xml
├── pom.xml
└── README.md

Configuration File (hibernate.cfg.xml)

Ensure that your hibernate.cfg.xml is correctly configured with the necessary database connection details and mappings.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
   <session-factory>
      <!-- Database connection settings -->
      <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
      <property name="connection.url">jdbc:mysql://localhost:3306/yourdb</property>
      <property name="connection.username">root</property>
      <property name="connection.password">password</property>

      <!-- JDBC connection pool settings -->
      <property name="connection.pool_size">1</property>

      <!-- SQL dialect -->
      <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

      <!-- Echo all executed SQL to stdout -->
      <property name="show_sql">true</property>

      <!-- Drop and re-create the database schema on startup -->
      <property name="hbm2ddl.auto">update</property>

      <!-- Mapping classes -->
      <mapping class="org.studyeasy.entity.Users"/>
   </session-factory>
</hibernate-configuration>

Implementing the Delete Operation

With the setup in place, let's delve into the implementation of the delete operation using Hibernate.

Step 1: Define the Entity Class

Ensure that your entity class (Users.java) is correctly annotated and mapped to your database table.

package org.studyeasy.entity;

import javax.persistence.*;

@Entity
@Table(name = "users")
public class Users {
    
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name = "user_id")
    private int id;
    
    @Column(name = "username")
    private String username;

    // Constructors
    public Users() {}

    public Users(String username) {
        this.username = username;
    }

    // Getters and Setters
    public int getId() { return id; }
    public void setId(int id) { this.id = id; }

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

Step 2: Create the Delete Method in App.java

Implement the delete functionality within your main application class.

package org.studyeasy;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.studyeasy.entity.Users;

public class App {
    public static void main(String[] args) {
        // Create SessionFactory
        SessionFactory factory = new Configuration()
                                 .configure("hibernate.cfg.xml")
                                 .addAnnotatedClass(Users.class)
                                 .buildSessionFactory();

        // Create Session
        Session session = factory.getCurrentSession();

        try {
            // Start a transaction
            session.beginTransaction();

            // Specify the user ID to delete
            int userIdToDelete = 3;

            // Retrieve the user object
            Users user = session.get(Users.class, userIdToDelete);

            // Delete the user if it exists
            if (user != null) {
                session.delete(user);
                System.out.println("Deleted user with ID: " + userIdToDelete);
            } else {
                System.out.println("User with ID " + userIdToDelete + " not found.");
            }

            // Commit the transaction
            session.getTransaction().commit();
        } finally {
            factory.close();
        }
    }
}

Code Walkthrough

Let's break down the App.java code step-by-step to understand how the delete operation is executed.

  1. SessionFactory Creation
    SessionFactory factory = new Configuration()
                             .configure("hibernate.cfg.xml")
                             .addAnnotatedClass(Users.class)
                             .buildSessionFactory();
        
    • Configures Hibernate using the hibernate.cfg.xml file.
    • Adds the Users annotated class.
    • Builds the SessionFactory, which is responsible for creating sessions.
  2. Session Initiation
    Session session = factory.getCurrentSession();
        
    • Obtains the current session from the SessionFactory.
  3. Transaction Management
    session.beginTransaction();
        
    • Begins a new transaction. All operations between beginTransaction() and commit() are part of this transaction.
  4. Retrieving the User to Delete
    int userIdToDelete = 3;
    Users user = session.get(Users.class, userIdToDelete);
        
    • Specifies the userId of the record to delete.
    • Retrieves the Users object corresponding to the specified userId.
  5. Deleting the User
    if (user != null) {
        session.delete(user);
        System.out.println("Deleted user with ID: " + userIdToDelete);
    } else {
        System.out.println("User with ID " + userIdToDelete + " not found.");
    }
        
    • Checks if the user exists.
    • If the user is found, invokes session.delete(user) to remove the record from the database.
    • Outputs a confirmation message.
  6. Committing the Transaction
    session.getTransaction().commit();
        
    • Commits the transaction, making the deletion permanent in the database.
  7. Closing the SessionFactory
    factory.close();
        
    • Closes the SessionFactory to release resources.

Expected Output

Upon running the application, you should see the following output in the console:

Deleted user with ID: 3

If the user with ID 3 does not exist, the output will be:

User with ID 3 not found.

Running the Application

To execute the delete operation, follow these steps:

  1. Ensure Database Connectivity
    • Verify that your database server is running.
    • Confirm that the hibernate.cfg.xml has the correct connection details.
  2. Compile the Application

    Use your preferred IDE (e.g., Eclipse, IntelliJ) or command-line tools to compile the project.

  3. Execute the App.java Class

    Run the App class. Hibernate will initiate the session, perform the delete operation, and commit the transaction.

  4. Verify the Deletion
    • Check your database to confirm that the user with ID 3 has been deleted.
    • Alternatively, you can run a read operation to attempt fetching the deleted user.

Best Practices for Deleting Records

Deleting records from a database is a sensitive operation. Adhering to best practices ensures data integrity and application stability.

1. Validate Before Deletion

Always check if the record exists before attempting to delete. This prevents exceptions and ensures that your application handles cases where the record may not be present.

if (user != null) {
    session.delete(user);
} else {
    // Handle the case where the user does not exist
}

2. Use Transactions Wisely

Encapsulate your delete operations within transactions. This allows you to roll back changes in case of failures, maintaining database consistency.

try {
    session.beginTransaction();
    // Perform delete operation
    session.getTransaction().commit();
} catch (Exception e) {
    session.getTransaction().rollback();
}

3. Handle Cascading Deletes Appropriately

If your entity relationships require cascading deletes, ensure that your Hibernate mappings are configured correctly to handle dependent records.

@OneToMany(mappedBy="user", cascade=CascadeType.ALL)
private Set orders;

4. Implement Soft Deletes When Necessary

Sometimes, you may not want to permanently delete records. Implementing soft deletes (marking records as inactive) can help in scenarios where data recovery might be needed.

@Entity
public class Users {
    // Other fields

    @Column(name = "active")
    private boolean active;

    // Getter and Setter
}

5. Log Deletion Activities

Maintain logs for delete operations to track changes and assist in debugging or auditing processes.

System.out.println("Deleted user with ID: " + userIdToDelete);

Conclusion

Deleting records using Hibernate is a straightforward yet powerful operation essential for robust data management in Java applications. By following the structured approach outlined in this guide—setting up Hibernate, implementing the delete method, and adhering to best practices—you can ensure that deletions are handled efficiently and safely.

Key Takeaways:

  • Understand the role of CRUD operations within Hibernate.
  • Properly configure Hibernate and your entity classes.
  • Implement deletion logic with validation and transaction management.
  • Follow best practices to maintain data integrity and application stability.

Embark on your Hibernate journey with confidence, and leverage the delete operation to maintain a clean and efficient database.

Note: That this article is AI generated.

Share Article

Back to Blog

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.