Hibernate Query Language - HQL

HQL is used to refined the hibernate query

List orders = session.createQuery(
    "from Order as order where order.total < ?")
    .setDouble(0, price)
    .list();

HQL

"from Order as order where order.total < ?")

Hibernate From Clause

Query for a Hibernate Persistent Entity

from somepackage.Order
from Order
from Order as o

Use 'o' as the alias

from Order as o

Hibernate Cross Join

Cross join tables

from tb1, tb2

Hibernate Left Join

from Order as order
left join order.items as item
  • By default, associated objects are loaded lazily

Adding a join condition in Hibernate query

from Order as order
left join order.items as item
with item.price > 10.0

Eager Loading in HQL

Use eager loading to fetch both table data in one SQL

from Order as order
left join fetch order.items as item

Fetch all column at once including those originally dedicated as lazy loading property

from Order order fetch all properties

Hibernate select clause

Return all columns of an order

select order
from Order as order
inner join order.items as item

Same as above

select order.items
from Order as order

Select table column(s)

select order.total
from Order as order

Use alias in result

select order.total as orderTotal
from Order as order

Return Multiple or Custom Objects using Hibernate HQL

Return multiple objects as an array of type Object[]

select order, item, order.total
from Order as order
inner join order.items as item

Return multiple objects as a list

select new list(order, item, order.total)
from Order as order
inner join order.items as item

Return a Java Object using a constructor

select new Order(order, shipping)
from Order as order
inner join order.shipping as shipping

Use functions in Hibernate HQL

select order.cost + order.shipping
from Order as order
select order.title || order.desc
from Order as order
select distinct order.title from Order order

Hibernate Aggregate Functions in HQL

select count(order)
from Order as order

Other aggregated functions

  • avg, sum, min, max

Hibernate where Clause

select order
from Order order, Item item
where order.id = item.orderId

Hibernate order, group by

select order
from Order order
order by cat.name order.count, order.total desc
select order
from Order order
group by order.id

Hibernate sub-query

Using sub-query in Hibernate

from Order as order
where order.total > (
    select avg(order.total) from Order
)
having order.id > 10