Hibernate CRUD Operations

In this tutorial, we will guide you through setting up and demonstrating CRUD (Create, Read, Update, Delete) operations using Hibernate 6+ with Java 21 and H2 database. We will create a simple application that performs CRUD operations on a Product entity. You’ll learn how to configure Hibernate with H2, a lightweight in-memory database, and how to implement CRUD functionality step-by-step.

What You’ll Learn:

  • Setting up a Maven project with Hibernate and H2.
  • Configuring Hibernate for database interaction.
  • Creating a Product entity class.
  • Implementing CRUD operations in Hibernate.
  • Demonstrating CRUD operations with a sample application.

Step 1: Set Up Your Maven Project

1.1 Create a Maven Project

  1. Open your IDE (e.g., IntelliJ IDEA, Eclipse).
  2. Create a new Maven project.

1.2 Add Required Dependencies

Update the pom.xml file to include dependencies for Hibernate and H2. The Maven Compiler Plugin is also configured to use Java 21.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>hibernate-crud-example</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <!-- Hibernate ORM --> <dependency> <groupId>org.hibernate.orm</groupId> <artifactId>hibernate-core</artifactId> <version>6.4.0.Final</version> </dependency> <!-- H2 Database --> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>2.1.214</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.10.1</version> <configuration> <source>21</source> <target>21</target> </configuration> </plugin> </plugins> </build> </project> 

Explanation:

  • Hibernate ORM: Provides the core Hibernate functionality to map Java objects to database tables.
  • H2 Database: A lightweight, in-memory database used for simplicity in this example.
  • Java 21: Latest version of Java used for this project.

Step 2: Configure Hibernate

2.1 Create hibernate.cfg.xml

In the src/main/resources directory, create a hibernate.cfg.xml file to configure Hibernate. This file contains settings for the H2 database and Hibernate properties.

<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property> <property name="hibernate.connection.driver_class">org.h2.Driver</property> <property name="hibernate.connection.url">jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1</property> <property name="hibernate.connection.username">sa</property> <property name="hibernate.connection.password"></property> <property name="hibernate.hbm2ddl.auto">update</property> <property name="hibernate.show_sql">true</property> </session-factory> </hibernate-configuration> 

Explanation:

  • hibernate.dialect: Defines the SQL dialect for H2 database.
  • hibernate.connection.url: Specifies the JDBC URL for H2 in-memory database.
  • hibernate.hbm2ddl.auto=update: Automatically updates the database schema based on the entity mappings.
  • hibernate.show_sql=true: Displays the SQL generated by Hibernate.

Step 3: Create the Product Entity

3.1 Create Product Entity Class

In the com.example.entity package, create a Product entity class that will be mapped to a table in the database.

package com.example.entity; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; @Entity public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private double price; // Getters and setters 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; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } } 

Explanation:

  • @Entity: Specifies that this class is a Hibernate entity mapped to a table.
  • @Id: Marks the primary key field.
  • @GeneratedValue: Automatically generates the ID using the IDENTITY strategy.

Step 4: Create Hibernate Utility Class

4.1 Create HibernateUtil Class

In the com.example.util package, create a HibernateUtil class to manage the Hibernate SessionFactory.

package com.example.util; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate.cfg.xml return new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { // Log the exception System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } public static void shutdown() { // Close caches and connection pools getSessionFactory().close(); } } 

Explanation:

  • SessionFactory: A singleton that manages the Hibernate sessions.
  • buildSessionFactory(): Builds the session factory using the configuration file.
  • shutdown(): Gracefully closes the session factory and releases resources.

Step 5: Implement CRUD Operations

5.1 Create ProductService Class

In the com.example.service package, create a ProductService class to manage CRUD operations for the Product entity.

package com.example.service; import com.example.entity.Product; import com.example.util.HibernateUtil; import org.hibernate.Session; import org.hibernate.Transaction; public class ProductService { public void createProduct(Product product) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = null; try { transaction = session.beginTransaction(); session.save(product); transaction.commit(); System.out.println("Product created successfully"); } catch (Exception e) { if (transaction != null) { transaction.rollback(); } e.printStackTrace(); } finally { session.close(); } } public Product getProduct(Long id) { Session session = HibernateUtil.getSessionFactory().openSession(); Product product = null; try { product = session.get(Product.class, id); if (product != null) { System.out.println("Product retrieved: " + product.getName()); } } catch (Exception e) { e.printStackTrace(); } finally { session.close(); } return product; } public void updateProduct(Product product) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = null; try { transaction = session.beginTransaction(); session.update(product); transaction.commit(); System.out.println("Product updated successfully"); } catch (Exception e) { if (transaction != null) { transaction.rollback(); } e.printStackTrace(); } finally { session.close(); } } public void deleteProduct(Long id) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = null; try { transaction = session.beginTransaction(); Product product = session.get(Product.class, id); if (product != null) { session.delete(product); transaction.commit(); System.out.println("Product deleted successfully"); } } catch (Exception e) { if (transaction != null) { transaction.rollback(); } e.printStackTrace(); } finally { session.close(); } } } 

Explanation:

  • createProduct(): Adds a product to the database.
  • getProduct(): Retrieves a product by ID.
  • updateProduct(): Updates an existing product.
  • deleteProduct(): Deletes a product by ID.

Step 6: Demonstrate CRUD Operations

6.1 Create MainApp Class

In the com.example.main package, create a MainApp class to demonstrate CRUD operations.

package com.example.main; import com.example.entity.Product; import com.example.service.ProductService; public class MainApp { public static void main(String[] args) { ProductService productService = new ProductService(); // Create a product Product product = new Product(); product.setName("Laptop"); product.setPrice(1500.00); productService.createProduct(product); // Retrieve the product Product retrievedProduct = productService.getProduct(product.getId()); // Update the product if (retrievedProduct != null) { retrievedProduct.setPrice(1400.00); productService.updateProduct(retrievedProduct); } // Delete the product productService.deleteProduct(retrievedProduct.getId()); } } 

Explanation:

  • MainApp demonstrates the full CRUD lifecycle:
    • Create: Adds a product.
    • Read: Retrieves the product.
    • Update: Updates the product’s price.
    • Delete: Deletes the product from the database.

Output

When you run the MainApp class, the output should be:

Product created successfully Product retrieved: Laptop Product updated successfully Product deleted successfully 

Explanation:

  • This output confirms that the product was successfully created, retrieved, updated, and deleted using Hibernate.

Conclusion

In this tutorial, we have successfully demonstrated how to perform CRUD operations using Hibernate 6+ and Java 21. We set up a Maven project, configured Hibernate, created an entity class, implemented CRUD operations, and demonstrated them in a sample application. This guide provides a strong foundation for building Hibernate-based applications with Java.


Comments