## 5.4.3 Hibernate Query Language (HQL)

GORM classes also support Hibernate's query language HQL, a very complete reference for which can be found Chapter 14. HQL: The Hibernate Query Language 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])

Or even named parameters:

    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

If you need to separate the query across multiple lines you can use a line continuation character:

    def results = Book.findAll("\
    from Book as b, \
         Author as a \
    where b.author = a and a.surname = ?", ['Smith'])

> Groovy multiline strings will NOT work with HQL queries

#### 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])