Menu

Hibernate Query Language (HQL)

Hibernate Query Language (HQL)

Querying Objects

HQL looks like SQL, but it works with entity classes and their fields, not tables and columns. Hibernate translates it into SQL for the configured database.

HQL supports filtering, sorting, joins, grouping, aggregate functions, and subqueries. You can omit the select clause when you return the whole entity.

Selection queries return data. Mutation queries run bulk update or delete statements.

List<Student> students = session
        .createSelectionQuery(
            "from Student s where s.name like :pattern order by s.name", Student.class)
        .setParameter("pattern", "A%")
        .getResultList();

int count = session
        .createMutationQuery("update Student s set s.status = :new where s.status = :old")
        .setParameter("new", Status.INACTIVE)
        .setParameter("old", Status.ACTIVE)
        .executeUpdate();

Code Explanation:

  • Student and s.name are the class and field names, not table and column names.
  • :pattern is a named parameter. Always pass values this way, never by joining strings, to prevent SQL injection.
  • createSelectionQuery() is for reads, and createMutationQuery() is for bulk changes.
  • executeUpdate() returns the number of rows changed.
  • A bulk update goes straight to the database. Entities already loaded in the session are not updated and may be stale.

Hibernate Tutorial

AP

Abhishek Pati



Learn via Video Course

Java Programming ( Telugu) Logo

Java Programming ( Telugu)

11 hrs



Get in Touch For Details