Hibernate HQL Subquery Tutorial

This tutorial will guide you through setting up and using the Hibernate Query Language (HQL) subquery with a MySQL database using the Product entity. We will demonstrate how to perform queries using subqueries to filter data based on conditions in other queries.


Hibernate Query Language (HQL) is a powerful query language similar to SQL but designed for Hibernate. It allows you to perform database operations using the object-oriented paradigm. In this tutorial, we will show you how to use subqueries in HQL to filter results based on conditions in other queries.

In this tutorial, we will:

  1. Set up a Maven project with necessary dependencies.
  2. Configure Hibernate and MySQL.
  3. Create an entity class (Product).
  4. Separate the Hibernate code into a DAO class.
  5. Demonstrate the use of HQL subqueries.

Step 1: Set Up Your Project

1.1 Create a Maven Project

Open your IDE and create a new Maven project.

1.2 Add Dependencies

Update your pom.xml file to include dependencies for Hibernate and MySQL.

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">


        <!-- Hibernate ORM -->

        <!-- MySQL Connector -->


Step 2: Configure Hibernate

2.1 Create hibernate.cfg.xml

Create a hibernate.cfg.xml file in the src/main/resources directory to configure database connection settings and Hibernate properties.

<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"

        <!-- JDBC Database connection settings -->
        <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_db</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">password</property>

        <!-- JDBC connection pool settings -->
        <property name="hibernate.c3p0.min_size">5</property>
        <property name="hibernate.c3p0.max_size">20</property>
        <property name="hibernate.c3p0.timeout">300</property>
        <property name="hibernate.c3p0.max_statements">50</property>
        <property name="hibernate.c3p0.idle_test_period">3000</property>

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

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

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

        <!-- Entities -->
        <mapping class="com.example.entity.Product"/>

Replace hibernate_db, root, and password with your MySQL database name and credentials.


  • hibernate.connection.driver_class specifies the JDBC driver class for MySQL.
  • hibernate.connection.url specifies the JDBC URL for the database connection.
  • hibernate.connection.username and hibernate.connection.password specify the database credentials.
  • hibernate.c3p0 properties configure the connection pool settings using C3P0.
  • hibernate.dialect specifies the SQL dialect to be used.
  • hibernate.show_sql and hibernate.format_sql properties are used to display and format the generated SQL statements.
  • hibernate.hbm2ddl.auto specifies the schema generation strategy.
  • The <mapping class="com.example.entity.Product"/> line maps the Product entity to the database.

Step 3: Create the Entity Class

Create an entity class Product that will be mapped to a table in the database. This class uses annotations to define the entity and its fields.

package com.example.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

public class Product {
    @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;


  • The @Entity annotation specifies that the class is an entity and is mapped to a database table.
  • The @Id annotation specifies the primary key of the entity.
  • The @GeneratedValue(strategy = GenerationType.IDENTITY) annotation specifies that the primary key is auto-incremented.

Step 4: Create the DAO Class

Create a DAO class to manage database operations using Hibernate.

4.1 Create ProductDAO

package com.example.dao;

import com.example.entity.Product;
import com.example.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.query.Query;

import java.util.List;

public class ProductDAO {
    public List<Product> getProductsCheaperThanMaxPrice() {
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            String subquery = "(select max(p.price) from Product p)";
            Query<Product> query = session.createQuery("from Product where price < " + subquery, Product.class);
            return query.list();

    public void insertSampleData() {
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            session.persist(new Product("Laptop", 1000.00));
            session.persist(new Product("Phone", 500.00));
            session.persist(new Product("Tablet", 300.00));

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


  • The ProductDAO class contains methods to interact with the database using Hibernate.
  • The getProductsCheaperThanMaxPrice method uses a subquery to get products cheaper than the maximum product price.
  • The insertSampleData method inserts sample data into the Product table.
  • The getAllProducts method retrieves all products from the database.

Step 5: Demonstrate the Use of HQL Subquery

Create a main class to demonstrate the use of the HQL subquery using the Product entity and ProductDAO class.

5.1 Create MainApp

package com.example.main;

import com.example.dao.ProductDAO;
import com.example.entity.Product;
import com.example.util.HibernateUtil;

import java.util.List;

public class MainApp {
    public static void main(String[] args) {
        ProductDAO productDAO = new ProductDAO();

        // Insert sample data

        // Display all products
        System.out.println("All Products:");
        List<Product> products = productDAO.getAllProducts();
        products.forEach(product -> System.out.println(product.getName() + " - " + product.getPrice()));

        // Perform HQL subquery
        List<Product> cheaperProducts = productDAO.getProductsCheaperThanMaxPrice();

        System.out.println("Products cheaper than the most expensive product:");
        cheaperProducts.forEach(product -> System.out.println(product.getName() + " - " + product.getPrice()));

        // Shut down the SessionFactory


  • The MainApp class demonstrates how to perform an HQL subquery using the ProductDAO class.
  • The insertSampleData method is called to insert sample data into the Product table.
  • The `get

AllProducts` method is called to retrieve all products from the database and display them.

  • The getProductsCheaperThanMaxPrice method is called to retrieve products cheaper than the most expensive product using a subquery, and the results are printed to the console.

5.2 Create HibernateUtil Class

Create a utility class HibernateUtil 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 {
            // Load the configuration and build the SessionFactory
            return new Configuration().configure().buildSessionFactory();
        } 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() {


  • The HibernateUtil class provides a singleton SessionFactory and a method to shut it down.
  • The buildSessionFactory method loads the Hibernate configuration from hibernate.cfg.xml and builds the SessionFactory.

Step 6: Run the Application

  1. Ensure your MySQL database is running and the connection details in hibernate.cfg.xml are correct.
  2. Run the MainApp class to load the Hibernate configuration, build the SessionFactory, insert sample data, perform the HQL subquery, and print the results.

Sample Output

If everything is set up correctly, running the MainApp class should produce output similar to the following:

All Products:
Laptop - 1000.0
Phone - 500.0
Tablet - 300.0
Products cheaper than the most expensive product:
Phone - 500.0
Tablet - 300.0


In this tutorial, we have successfully demonstrated how to create and configure a Hibernate configuration file (hibernate.cfg.xml) to connect to a MySQL database using the Product entity and perform an HQL subquery. We separated the Hibernate code into a DAO class, configured the project dependencies, created an entity class, set up the Hibernate configuration file, and demonstrated the use of the HQL subquery. This guide provides a solid foundation for using HQL subqueries with Hibernate and a MySQL database in your applications.