Hibernate Java

Hibernate – Sort (Order) Query Results

Hibernate – Sort (Order) Query Results

Sorting query results in Hibernate can be done via HQL's ORDER BY clause or the Criteria API's orderBy() method. This tutorial demonstrates how to sort a Product list by price, name, and multiple columns — in both ascending and descending order.

Prerequisites

  • Java 8 or later
  • Hibernate 5.x
  • MySQL database
  • Maven project

Database Table

CREATE TABLE product (
  id          INT          NOT NULL AUTO_INCREMENT,
  name        VARCHAR(45)  DEFAULT NULL,
  price       DECIMAL(10,0) DEFAULT NULL,
  quantity    INT          DEFAULT NULL,
  description VARCHAR(450) DEFAULT NULL,
  active      TINYINT(1)   DEFAULT NULL,
  created_at  DATETIME     NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id)
);

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!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="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/java9rdb</property>
    <property name="connection.username">root</property>
    <property name="connection.password">yourpassword</property>
    <property name="dialect">org.hibernate.dialect.MySQL8Dialect</property>
    <property name="show_sql">true</property>
    <property name="hbm2ddl.auto">update</property>
    <mapping class="com.java9r.model.Product"/>
  </session-factory>
</hibernate-configuration>

Product Entity

package com.java9r.model;

import javax.persistence.*;

@Entity
@Table(name = "product")
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "name", length = 45)
    private String name;

    @Column(name = "price")
    private Long price;

    @Column(name = "quantity")
    private Integer quantity;

    @Column(name = "active")
    private Boolean active;

    public Product() {}

    public Integer getId()      { return id; }
    public String  getName()    { return name; }
    public Long    getPrice()   { return price; }
    public Integer getQuantity(){ return quantity; }
    public Boolean getActive()  { return active; }

    @Override
    public String toString() {
        return String.format("Product{id=%d, name='%s', price=%d, qty=%d}",
                             id, name, price, quantity);
    }
}

HibernateUtil

package com.java9r.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

    private static final SessionFactory sessionFactory =
            new Configuration().configure().buildSessionFactory();

    public static SessionFactory getSessionFactory() { return sessionFactory; }
    public static void shutdown()                    { sessionFactory.close(); }
}

ProductDAO – Sort Examples

package com.java9r.dao;

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

import javax.persistence.criteria.*;
import java.util.List;

public class ProductDAO {

    // ------------------------------------------------------------------
    // Method 1: HQL ORDER BY — ascending by price
    // ------------------------------------------------------------------
    public List<Product> sortByPriceAsc() {
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            return session.createQuery(
                "FROM Product ORDER BY price ASC", Product.class).list();
        }
    }

    // ------------------------------------------------------------------
    // Method 2: HQL ORDER BY — descending by price
    // ------------------------------------------------------------------
    public List<Product> sortByPriceDesc() {
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            return session.createQuery(
                "FROM Product ORDER BY price DESC", Product.class).list();
        }
    }

    // ------------------------------------------------------------------
    // Method 3: HQL ORDER BY — alphabetical by name
    // ------------------------------------------------------------------
    public List<Product> sortByNameAsc() {
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            return session.createQuery(
                "FROM Product ORDER BY name ASC", Product.class).list();
        }
    }

    // ------------------------------------------------------------------
    // Method 4: HQL ORDER BY — multiple columns
    //           Sort by active status (true first), then by price descending
    // ------------------------------------------------------------------
    public List<Product> sortByActiveAndPrice() {
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            return session.createQuery(
                "FROM Product ORDER BY active DESC, price DESC", Product.class).list();
        }
    }

    // ------------------------------------------------------------------
    // Method 5: Criteria API ORDER BY — type-safe, dynamic sort direction
    // ------------------------------------------------------------------
    public List<Product> sortByPriceCriteria(boolean ascending) {
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            CriteriaBuilder cb = session.getCriteriaBuilder();
            CriteriaQuery<Product> cq = cb.createQuery(Product.class);
            Root<Product> root = cq.from(Product.class);

            cq.select(root).orderBy(
                ascending ? cb.asc(root.get("price"))
                          : cb.desc(root.get("price"))
            );

            return session.createQuery(cq).getResultList();
        }
    }
}

Main Class

package com.java9r;

import com.java9r.dao.ProductDAO;
import com.java9r.model.Product;
import com.java9r.util.HibernateUtil;

import java.util.List;

public class SortProductsMain {

    public static void main(String[] args) {
        ProductDAO dao = new ProductDAO();

        System.out.println("=== Sort by Price ASC ===");
        printProducts(dao.sortByPriceAsc());

        System.out.println("\n=== Sort by Price DESC ===");
        printProducts(dao.sortByPriceDesc());

        System.out.println("\n=== Sort by Name (A-Z) ===");
        printProducts(dao.sortByNameAsc());

        System.out.println("\n=== Sort by Active DESC, Price DESC ===");
        printProducts(dao.sortByActiveAndPrice());

        System.out.println("\n=== Sort by Price DESC (Criteria API) ===");
        printProducts(dao.sortByPriceCriteria(false));

        HibernateUtil.shutdown();
    }

    private static void printProducts(List<Product> products) {
        System.out.println("Found " + products.size() + " products:");
        products.forEach(System.out::println);
    }
}

Expected Output

=== Sort by Price ASC ===
Found 5 products:
Product{id=5, name='Keyboard', price=2500, qty=100}
Product{id=4, name='Monitor', price=15000, qty=20}
Product{id=2, name='Smartphone', price=25000, qty=50}
Product{id=3, name='Tablet', price=35000, qty=30}
Product{id=1, name='Laptop', price=75000, qty=10}

=== Sort by Price DESC ===
Found 5 products:
Product{id=1, name='Laptop', price=75000, qty=10}
Product{id=3, name='Tablet', price=35000, qty=30}
Product{id=2, name='Smartphone', price=25000, qty=50}
Product{id=4, name='Monitor', price=15000, qty=20}
Product{id=5, name='Keyboard', price=2500, qty=100}

=== Sort by Name (A-Z) ===
Found 5 products:
Product{id=5, name='Keyboard', price=2500, qty=100}
Product{id=1, name='Laptop', price=75000, qty=10}
Product{id=4, name='Monitor', price=15000, qty=20}
Product{id=2, name='Smartphone', price=25000, qty=50}
Product{id=3, name='Tablet', price=35000, qty=30}

HQL vs Criteria API for Sorting

Feature HQL ORDER BY Criteria API orderBy()
Readability High — SQL-like syntax Verbose but structured
Type safety No (field names as strings) Yes (compile-time checked)
Dynamic sort direction Difficult (string building) Easy — pass cb.asc() or cb.desc()
Multi-column sort ORDER BY col1, col2 .orderBy(order1, order2)

Summary

Sorting in Hibernate is straightforward with both HQL and the Criteria API. Use HQL ORDER BY for simple, fixed sort requirements — it reads like SQL and is easy to understand. Use the Criteria API when the sort direction or column is determined at runtime (e.g., from a user-selected column header in a table). Both approaches translate directly to SQL ORDER BY and support multiple sort columns.

Topics: Hibernate Java
← Newer Post Older Post →

Comments

https://www.blogger.com/comment/frame/6690124484600543990?po=5641462332608684366&hl=en&saa=85391&origin=https://www.java9r.com