7.4.5 Hibernate Query Language (HQL) - Reference Documentation
Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith, Lari Hotari
Version: 3.1.1
7.4.5 Hibernate Query Language (HQL)
GORM classes also support Hibernate's query language HQL, a very complete reference for which can be found in the Hibernate documentation of the Hibernate documentation.GORM provides a number of methods that work with HQL including find, findAll and executeQuery. An example of a query can be seen below:def results =
Book.findAll("from Book as b where b.title like 'Lord of the%'")
Positional and Named Parameters
In this case the value passed to the query is hard coded, however you can equally use positional parameters:def results = Book.findAll("from Book as b where b.title like ?", ["The Shi%"])
def author = Author.findByName("Stephen King") def books = Book.findAll("from Book as book where book.author = ?", [author])
def results = Book.findAll("from Book as b " + "where b.title like :search or b.author like :search", [search: "The Shi%"])
def author = Author.findByName("Stephen King") def books = Book.findAll("from Book as book where book.author = :author", [author: author])
Multiline Queries
--As of Grails 3.0.3, Triple-quoted Groovy multiline Strings now work properly with HQL queries. -Use the line continuation character to separate the query across multiple lines:
def results = Book.findAll("\
from Book as b, \
Author as a \
where b.author = a and a.surname = ?", ['Smith'])
def results = Book.findAll(""" from Book as b, Author as a where b.author = a and a.surname = ?", ['Smith'] """)
Pagination and Sorting
You can also perform pagination and sorting whilst using HQL queries. To do so simply specify the pagination options as a Map at the end of the method call and include an "ORDER BY" clause in the HQL:def results = Book.findAll("from Book as b where " + "b.title like 'Lord of the%' " + "order by b.title asc", [max: 10, offset: 20])