Hibernate HQL CRUD Example

📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.

🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.

▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

In this tutorial, we will demonstrate how to perform basic CRUD (Create, Read, Update, Delete) operations using Hibernate Query Language (HQL) with a Todo entity. We will create a simple application to manage Todo entities with Hibernate. In this tutorial, we use the latest version of Hibernate 6.4.

HQL (Hibernate Query Language) is an object-oriented query language similar to SQL, but it is designed for querying entities stored in a relational database using Hibernate ORM framework. HQL allows you to write queries in a way that is closely aligned with the object model of the application, rather than the relational model of the database.

Prerequisites

Before we start, ensure you have the following:

  • Java Development Kit (JDK) installed
  • Apache Maven installed
  • An IDE (such as IntelliJ IDEA, Eclipse, or VS Code) installed

Step 1: Setting Up the Hibernate Project

1.1 Create a Maven Project

  1. Open your IDE and create a new Maven project.

  2. Configure the pom.xml file:

Add the following dependencies to your pom.xml:

<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-example</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.hibernate.orm</groupId> <artifactId>hibernate-core</artifactId> <version>6.4.0.Final</version> </dependency> <dependency> <groupId>org.hibernate.orm</groupId> <artifactId>hibernate-hikaricp</artifactId> <version>6.4.0.Final</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.32</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.7.32</version> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>2.1.210</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>17</source> <target>17</target> </configuration> </plugin> </plugins> </build> </project> 

1.2 Configure Hibernate

Create a file named hibernate.cfg.xml in the src/main/resources directory with the following content:

<!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> <property name="hibernate.format_sql">true</property> </session-factory> </hibernate-configuration> 

1.3 Create the Todo Entity

Create a Todo class in the com.example.hibernateexample.model package:

package com.example.hibernateexample.model; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; @Entity public class Todo { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; private String description; private boolean completed; // Getters and Setters public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public boolean isCompleted() { return completed; } public void setCompleted(boolean completed) { this.completed = completed; } } 

1.4 Create the Hibernate Utility Class

Create a HibernateUtil class in the com.example.hibernateexample.util package:

package com.example.hibernateexample.util; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { Configuration configuration = new Configuration(); configuration.configure("hibernate.cfg.xml"); return configuration.buildSessionFactory(new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()).build()); } catch (Throwable ex) { System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } public static void shutdown() { getSessionFactory().close(); } } 

Step 2: Performing CRUD Operations with HQL

2.1 INSERT Operation

Create a TodoDao class in the com.example.hibernateexample.dao package to handle database operations:

package com.example.hibernateexample.dao; import com.example.hibernateexample.model.Todo; import com.example.hibernateexample.util.HibernateUtil; import org.hibernate.Session; import org.hibernate.Transaction; public class TodoDao { public void saveTodo(Todo todo) { Transaction transaction = null; try (Session session = HibernateUtil.getSessionFactory().openSession()) { transaction = session.beginTransaction(); session.save(todo); transaction.commit(); } catch (Exception e) { if (transaction != null) { transaction.rollback(); } e.printStackTrace(); } } } 

2.2 SELECT Operation

Add a method to the TodoDao class to retrieve all todos:

import java.util.List; import org.hibernate.query.Query; public List<Todo> getTodos() { try (Session session = HibernateUtil.getSessionFactory().openSession()) { Query<Todo> query = session.createQuery("from Todo", Todo.class); return query.list(); } } 

2.3 UPDATE Operation

Add a method to the TodoDao class to update a todo:

public void updateTodo(Todo todo) { Transaction transaction = null; try (Session session = HibernateUtil.getSessionFactory().openSession()) { transaction = session.beginTransaction(); session.update(todo); transaction.commit(); } catch (Exception e) { if (transaction != null) { transaction.rollback(); } e.printStackTrace(); } } 

2.4 DELETE Operation

Add a method to the TodoDao class to delete a todo:

public void deleteTodo(Long id) { Transaction transaction = null; try (Session session = HibernateUtil.getSessionFactory().openSession()) { transaction = session.beginTransaction(); Todo todo = session.get(Todo.class, id); if (todo != null) { session.delete(todo); System.out.println("Todo is deleted"); } transaction.commit(); } catch (Exception e) { if (transaction != null) { transaction.rollback(); } e.printStackTrace(); } } 

Step 3: Testing the CRUD Operations

Create a Main class in the com.example.hibernateexample package to test the CRUD operations:

package com.example.hibernateexample; import com.example.hibernateexample.dao.TodoDao; import com.example.hibernateexample.model.Todo; import java.util.List; public class Main { public static void main(String[] args) { TodoDao todoDao = new TodoDao(); // Insert a todo Todo todo1 = new Todo(); todo1.setTitle("Todo 1"); todo1.setDescription("Description 1"); todo1.setCompleted(false); todoDao.saveTodo(todo1); // Insert another todo Todo todo2 = new Todo(); todo2.setTitle("Todo 2"); todo2.setDescription("Description 2"); todo2.setCompleted(false); todoDao.saveTodo(todo2); // Select all todos List<Todo> todos = todoDao.getTodos(); todos.forEach(t -> System.out.println(t.getTitle() + " - " + t.getDescription() + " - " + t.isCompleted())); // Update a todo todo1.setCompleted(true); todoDao.updateTodo(todo 1); // Select all todos again todos = todoDao.getTodos(); todos.forEach(t -> System.out.println(t.getTitle() + " - " + t.getDescription() + " - " + t.isCompleted())); // Delete a todo todoDao.deleteTodo(todo2.getId()); // Select all todos again todos = todoDao.getTodos(); todos.forEach(t -> System.out.println(t.getTitle() + " - " + t.getDescription() + " - " + t.isCompleted())); } } 

Conclusion

In this tutorial, we set up a simple Hibernate project using Maven and demonstrated how to perform basic CRUD operations using Hibernate Query Language (HQL). We created a Todo entity and a TodoDao class to handle database operations. We tested the CRUD operations in a Main class. By following this structure, you can extend and customize the application as needed.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare