13

I want to integrate sort, order, max and offset in a findAll query. The following works fine:

def books = Book.findAll("from Book as b where b.approved=true order by b.dateCreated  desc", [max: max, offset: offset])

But what I want is:

def books = Book.findAll("from Book as b where b.approved=true", [sort: 'dateCreated', order: 'desc', max: max, offset: offset])

This does not work. How do I have to rewrite this?

0

4 Answers 4

9

Using "findAllBy" because it supports sort and order.

def results = Book.findAllByTitle("The Shining",
             [max: 10, sort: "title", order: "desc", offset: 100])

Click here for details.

8

HQL doesn't support sort and order as parameters, so you need to include the "order by" as part of the HQL expression

def books = Book.findAll("from Book as b where b.approved=true"
  + " order by b.dateCreated desc", [max: max, offset: offset])

(or in this case just use Book.findAllByApproved(true, [...]) instead of HQL).

So if the sort and order are variables you need a trick like

def books = Book.findAll("from Book as b where b.approved=true"
  + (params.sort ? " order by b.${params.sort} ${params.order}" : ''), 
  [max: max, offset: offset])
2
  • This does not answer the question. How can I include sort and order as variable in this query?
    – confile
    Nov 19, 2012 at 9:42
  • 1
    @userWebMobile it's a "ternary conditional" - (condition ? valueIfTrue : valueIfFalse) - to cope with the possibility that params.sort might not be set, in which case you don't need an order by clause at all. If you know you will always have some sort and order values then just use the "order by b.${params.sort} ${params.order}" bit unconditionally. Nov 19, 2012 at 12:31
7

Using a where query works for me:

def books = Book.where{approved == true}.list(sort: 'dateCreated', order: 'desc', max: max, offset: offset)

Or with params straight from the page:

def books = Book.where{approved == true}.list(params)

1

I am assuming you are calling fetching the list of books in a controller or a service class.

If you are calling this from a controller action, then a magic variable "params" is already available to you. For example, if you request the page as follows

book/list?max=10&offset=2

then "params" will already have those values mapped automagically.

You can add more items to the params map as follows

params.sort = "dateCreated"
params.order = "desc"

Once you have build your params as desired, then you can use Grails dynamic query as follows

def books = Book.findAllByApproved(true, params)
// use "books" variable as you wish

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.