Hibernate Java

Hibernate CRUD – Add, Update, and Delete Records

Hibernate CRUD – Add, Update, and Delete Records

CRUD (Create, Read, Update, Delete) operations are the backbone of any data-driven application. Hibernate provides a clean, object-oriented way to perform these operations without writing raw SQL. This tutorial covers how to add a new record, update an existing one, and delete a record using Hibernate's Session API.

We will use the same Product entity and HibernateUtil from the Find All Records tutorial. If you haven't set that up yet, start there first.

1. Add a New Record (Create)

To insert a new row into the database, create a new entity object and call session.save() or session.persist() within a transaction.


package com.java9r;

import com.java9r.model.Product;
import com.java9r.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 * Hibernate – Insert a new Product record.
 */
public class HibernateAddRecord {

    public static void main(String[] args) {

        // Create a new Product object (no id needed – auto-generated)
        Product product = new Product("Gaming Laptop", 95000.00, 15);

        Transaction tx = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            tx = session.beginTransaction();

            // save() inserts the record and assigns the generated id
            session.save(product);

            tx.commit();
            System.out.println("Product saved with id: " + product.getId());
            System.out.println("Saved: " + product);

        } catch (Exception e) {
            if (tx != null) tx.rollback();  // rollback on error
            e.printStackTrace();
        } finally {
            HibernateUtil.shutdown();
        }
    }
}

Output


Hibernate: insert into products (name, price, quantity) values (?, ?, ?)
Product saved with id: 6
Saved: Product{id=6, name='Gaming Laptop', price=95000.00, qty=15}

save() vs persist() vs saveOrUpdate()

Method Returns Works Outside Transaction? On Detached Entity
save() Generated id Yes (not recommended) Inserts new row
persist() void No Throws exception
saveOrUpdate() void No Updates if id exists

2. Update an Existing Record

To update a record, load it first with session.get(), modify its fields, then call session.update() — or simply let Hibernate detect the changes automatically if the entity is in the persistent state (loaded within the same session).


package com.java9r;

import com.java9r.model.Product;
import com.java9r.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 * Hibernate – Update an existing Product record.
 * Best practice: load + modify in same session (dirty checking handles the update).
 */
public class HibernateUpdateRecord {

    public static void main(String[] args) {

        Transaction tx = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            tx = session.beginTransaction();

            // Step 1: Load the product by id
            Product product = session.get(Product.class, 2);  // load product with id=2

            if (product != null) {
                System.out.println("Before update: " + product);

                // Step 2: Modify the fields
                product.setPrice(22000.00);   // update price
                product.setQuantity(75);      // update quantity

                // Step 3: Hibernate's dirty checking automatically detects changes
                // session.update(product) is optional here – Hibernate will issue UPDATE
                // automatically when the transaction commits

            } else {
                System.out.println("Product not found with id=2");
            }

            tx.commit();

            // Reload to confirm
            Product updated = session.get(Product.class, 2);
            System.out.println("After update:  " + updated);

        } catch (Exception e) {
            if (tx != null) tx.rollback();
            e.printStackTrace();
        } finally {
            HibernateUtil.shutdown();
        }
    }
}

Output


Hibernate: select ... from products where id=2
Before update: Product{id=2, name='Smartphone', price=25000.00, qty=50}
Hibernate: update products set name=?, price=?, quantity=? where id=?
After update:  Product{id=2, name='Smartphone', price=22000.00, qty=75}

Updating a Detached Entity


// If you have an entity from outside a session (detached), use merge()
Product detached = new Product();
detached.setId(3);
detached.setName("Tablet Pro");
detached.setPrice(40000.00);
detached.setQuantity(25);

try (Session session = HibernateUtil.getSessionFactory().openSession()) {
    Transaction tx = session.beginTransaction();
    session.merge(detached);  // re-attaches and updates
    tx.commit();
}

3. Delete a Record

To delete a record, load it by its primary key and call session.delete().


package com.java9r;

import com.java9r.model.Product;
import com.java9r.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 * Hibernate – Delete a Product record by id.
 */
public class HibernateDeleteRecord {

    public static void main(String[] args) {

        int idToDelete = 5;  // delete product with id=5

        Transaction tx = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            tx = session.beginTransaction();

            Product product = session.get(Product.class, idToDelete);

            if (product != null) {
                System.out.println("Deleting: " + product);
                session.delete(product);
                System.out.println("Deleted successfully.");
            } else {
                System.out.println("No product found with id=" + idToDelete);
            }

            tx.commit();

        } catch (Exception e) {
            if (tx != null) tx.rollback();
            e.printStackTrace();
        } finally {
            HibernateUtil.shutdown();
        }
    }
}

Output


Hibernate: select ... from products where id=5
Deleting: Product{id=5, name='Keyboard', price=2500.00, qty=100}
Hibernate: delete from products where id=?
Deleted successfully.

Bulk Delete Using HQL

For deleting multiple records matching a condition, use an HQL DELETE query (more efficient than loading each entity):


try (Session session = HibernateUtil.getSessionFactory().openSession()) {
    Transaction tx = session.beginTransaction();

    // Delete all products with price less than 5000
    int deleted = session.createQuery(
        "DELETE FROM Product WHERE price < :threshold")
        .setParameter("threshold", 5000.0)
        .executeUpdate();

    tx.commit();
    System.out.println("Deleted " + deleted + " cheap products.");
}

Common Mistakes to Avoid

  • Not using transactions: Always wrap write operations in a transaction. Without it, changes may not be committed.
  • Not calling rollback on exception: Always call tx.rollback() in the catch block to avoid leaving the database in a partial state.
  • Calling delete on a transient object: You must load the entity from the session before deleting. Passing a detached object with only the id set will throw an exception.
  • Modifying after session close: Once the session is closed, the entity is detached and changes will not be persisted automatically.

Summary

Hibernate's Session API makes CRUD operations straightforward. Use session.save() to insert, load and modify within the same session for updates (Hibernate's dirty checking handles the SQL automatically), and session.delete() to remove records. Always wrap write operations in transactions and handle rollback in your catch block. For bulk updates or deletes affecting many rows, use HQL DML queries instead of loading each entity individually — this is significantly more efficient at scale.

Topics: Hibernate Java
← Newer Post Older Post →