Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 39 ยท HQL, Criteria and Native Queries

HQL Basics: Querying Entities, Not Tables

Learn HQL, Hibernate's object query language - select entities, filter with named parameters, sort, page and run typed queries, with a runnable HQL-to-SQL translator stand-in.

SQL talks about tables and columns. Your Java code talks about classes and fields. HQL (the Hibernate Query Language) is the bridge: you write queries against your entities, and Hibernate translates them to the SQL dialect of your database. HQL looks like SQL, but Book is the class and b.price is the field, so renaming a column in the mapping never breaks your queries.

Since Hibernate 6, HQL is a superset of JPQL and follows the SQL standard closely. It supports joins, aggregates, subqueries, case expressions, functions and window functions. In this lesson you learn the building blocks: the from clause, select, where, parameters, ordering, paging and typed results.

Hibernate does not run in our in-browser sandbox, so its code appears as read-only blocks. The runnable examples build a small stand-in with JDBC and an in-memory H2 database that shows what Hibernate does for you: it turns an entity query into SQL with bound parameters.

The shape of an HQL query

The smallest query is just an entity name. Hibernate returns managed Book objects, not rows:

Java
List<Book> all = session.createSelectionQuery("from Book", Book.class).getResultList();

An alias makes longer queries readable, and select chooses what comes back:

Java
// entities
"from Book b where b.price < 20 order by b.title"

// a single field
"select b.title from Book b"

// several fields as a tuple (Object[]) or a record
"select b.title, b.price from Book b"

// a constructor expression builds a DTO directly
"select new com.example.BookSummary(b.title, b.price) from Book b"

Notes:

  • Entity and field names are case sensitive (Book, b.title); keywords such as from or WHERE are not.
  • The entity name defaults to the unqualified class name, or the name given in @Entity.
  • select is optional when you want the whole entity.

Named parameters, never string concatenation

Never build HQL by gluing user input into a string. It opens the door to injection, defeats query plan caching and breaks on quotes. Use named parameters (:name):

Java
List<Book> books = session.createSelectionQuery(
        "from Book b where b.price < :max and b.title like :text", Book.class)
    .setParameter("max", new BigDecimal("20.00"))
    .setParameter("text", "%Java%")
    .getResultList();

Positional parameters (?1) exist, but names survive refactoring much better. Hibernate sends them as JDBC bind variables, so the database can reuse its execution plan.

Sorting, limiting and paging

Java
List<Book> page = session.createSelectionQuery(
        "from Book b order by b.price desc, b.title", Book.class)
    .setFirstResult(20)    // offset: skip the first 20 rows
    .setMaxResults(10)     // limit: return at most 10
    .getResultList();

The API methods are portable (Hibernate writes the right limit/offset/fetch first syntax for your database) and let you pass values as parameters. setMaxResults(1) is the standard way to ask for "the first matching row".

For a single value there are two helpers: getSingleResult() throws NoResultException if empty and NonUniqueResultException if more than one row matches; getSingleResultOrNull() returns null when nothing matches.

Filtering expressions

Need HQL
Comparison =, <>, <, <=, >, >=
Range b.price between 10 and 30
Set b.status in (:statuses) (pass a collection)
Text b.title like :p, lower(b.title) like :p, b.title ilike :p
Null b.subtitle is null, is not null
Boolean logic and, or, not and parentheses
Collection b.tags is empty, :tag member of b.tags
Case case when b.price < 10 then 'cheap' else 'regular' end

The in operator accepts a collection parameter: setParameter("statuses", List.of(Status.NEW, Status.SALE)). Enum values bind through the mapping, so you never write the raw column value.

Stand-in: an HQL-to-SQL translator

To see the idea without Hibernate, this program keeps a tiny metadata map (entity name to table, field to column) and rewrites a simple HQL string to SQL, then runs it with bound parameters on H2. Real Hibernate does the same thing with a full parser and a much richer model.

Java A tiny HQL-to-SQL translator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The query never mentions unit_price. It mentions b.price, and the metadata decides the column. That indirection is what lets you rename columns or change the mapping without touching queries.

Projections and DTOs

Loading a whole entity is wasteful when a screen needs two fields. Choose the right shape:

Shape Query Result
Entity from Book b managed Book, tracked for changes
Scalar select b.title from Book b String
Tuple select b.title, b.price from Book b Object[] or a record
DTO select new BookSummary(b.title, b.price) from Book b your class, not managed

Hibernate 6 can also map straight into a Java record with createSelectionQuery(hql, BookSummary.class) when the select list matches the record components. Projections are read-only snapshots: nothing is tracked, so edits are never flushed. That makes them ideal for list screens and reports.

The next stand-in compares the two result shapes with plain JDBC: the entity-like version fills a mutable object per row, the DTO version fills an immutable record from only the columns it needs.

Java Entity-like objects versus DTO records

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Common mistakes

  • Using table or column names in HQL. from books fails: use the entity name Book. If you need raw table names, use a native query.
  • Concatenating user input. Always use parameters.
  • Paging with a collection fetch join. join fetch on a collection plus setMaxResults makes Hibernate page in memory. Page the parent IDs first, then fetch (see fetch strategies).
  • Expecting DTOs to track changes. Only managed entities are dirty-checked.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the from clause of an HQL query name?

    HQL queries entities. Hibernate uses the mapping to find the table and columns.
  2. 2. How should user input be passed into an HQL query?

    Named parameters become JDBC bind variables, which prevents injection and allows plan reuse.
  3. 3. What is true about the objects returned by a constructor expression such as select new BookSummary(b.title, b.price) from Book b?

    Constructor expressions build plain objects, so changes to them are never flushed.
  4. 4. Which call returns null instead of throwing when no row matches?

    getSingleResultOrNull() returns null for an empty result, while getSingleResult() throws NoResultException.

Summary

  • HQL queries entities and fields; Hibernate generates the SQL for your database.
  • Use select for projections, select new for DTOs, and named parameters for values.
  • Paging uses setFirstResult and setMaxResults; single results have strict and lenient variants.
  • Projections are cheap and read-only; entities are tracked and can be modified.

Next: HQL Joins, Aggregates and Subqueries