Hibernate Query Language INSERT, UPDATE, SELECT and DELETE Example

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

Introduction to HQL (Hibernate Query Language)

What is HQL?

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 the 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.

Key Points of HQL:

  • Object-Oriented: HQL queries are written in terms of the object model and the entities defined in the application, not the database tables and columns.
  • Database Independent: HQL is designed to be database-independent, allowing you to switch databases without changing your queries.
  • Powerful and Flexible: HQL supports all CRUD operations and provides powerful features like joins, aggregations, and subqueries.

Basic Syntax of HQL:

  • SELECT Queries: Used to retrieve data from the database.
    SELECT s FROM Student s WHERE s.firstName = 'Ramesh'
    
  • INSERT Queries: Not directly supported, but can be achieved using entity manipulation.
  • UPDATE Queries: Used to update existing records.
    UPDATE Student s SET s.email = '[email protected]' WHERE s.id = 1
    
  • DELETE Queries: Used to delete records.
    DELETE FROM Student s WHERE s.id = 1
    

Example of HQL:

Here's a simple example demonstrating the usage of HQL to fetch all students with a specific first name:

String hql = "FROM Student S WHERE S.firstName = :firstName";
Query query = session.createQuery(hql);
query.setParameter("firstName", "Ramesh");
List results = query.list();

In this example:

  • FROM Student S specifies that we are querying the Student entity.
  • WHERE S.firstName = :firstName applies a filter to only fetch students with the first name "Ramesh".
  • session.createQuery(hql) creates an HQL query from the session.
  • query.setParameter("firstName", "Ramesh") sets the parameter value.
  • query.list() executes the query and returns the results as a list.

HQL provides a powerful way to interact with your database through the object-oriented model of your application, making it easier to write and maintain queries.

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 Product Entity

Create a Product 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 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;
    }
}

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 ProductDao class in the com.example.hibernateexample.dao package to handle database operations:

package com.example.hibernateexample.dao;

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

public class ProductDao {

    public void saveProduct(Product product) {
        Transaction transaction = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            transaction = session.beginTransaction();
            session.save(product);
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }
}

2.2 SELECT Operation

Add a method to the ProductDao class to retrieve all products:

import java.util.List;
import org.hibernate.query.Query;

public List<Product> getProducts() {
    try (Session session = HibernateUtil.getSessionFactory().openSession()) {
        Query<Product> query = session.createQuery("from Product", Product.class);
        return query.list();
    }
}

2.3 UPDATE Operation

Add a method to the ProductDao class to update a product:

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

2.4 DELETE Operation

Add a method to the ProductDao class to delete a product:

public void deleteProduct(Long id) {
    Transaction transaction = null;
    try (Session session = HibernateUtil.getSessionFactory().openSession()) {
        transaction = session.beginTransaction();
        Product product = session.get(Product.class, id);
        if (product != null) {
            session.delete(product);
            System.out.println("Product 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.ProductDao;
import com.example.hibernateexample.model.Product;

import java.util.List;

public class Main {
    public static void main(String[] args) {
        ProductDao productDao = new ProductDao();

        // Insert a product
        Product product1 = new Product();
        product1.setName("Product 1");
        product1.setPrice(100.00);
        productDao.saveProduct(product1);

        // Insert another product
        Product product2 = new Product();
        product2.setName("Product 2");
        product2.setPrice(200.00);
        productDao.saveProduct(product2);

        // Select all products
        List<Product> products = productDao.getProducts();
        products.forEach(p -> System.out.println(p.getName() + " - " + p.getPrice()));

        // Update a product
        product1.setPrice(150.00);
        productDao.updateProduct(product1);

        // Select all products again
        products = productDao.getProducts();
        products.forEach(p -> System.out.println(p.getName() + " - " + p.getPrice()));

        // Delete a product
        productDao.deleteProduct(product2.getId());

        // Select all products again


        products = productDao.getProducts();
        products.forEach(p -> System.out.println(p.getName() + " - " + p.getPrice()));
    }
}

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 Product entity and a ProductDao 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

  1. I don't understand the insert statement. What if I have a Student passed in as a parameter? How do we pass those values to the query?

    ReplyDelete

Post a Comment

Leave Comment