It just takes 15 seconds. Send your
details and we’ll get back to you soon.

Using aliases in aggregate functions of criteria queries

When using criteria queries, many times we encounter a use case where we need to order our result not on any field of domain class but on our result set, in these cases aliases can be used.

In my project, use case was to find most liked products from the domain:

Date dateCreated
Product product

To find the result, the query I used was :

ProductStat.createCriteria().list() {
            projections {
                count("product", "totalProducts")  // alias totalProducts
            order("totalProducts", "desc")

In this way using alias “totalProducts” I was able to order the result according to the count of products.


Posted in Grails | Tagged , , , .

2 Responses to Using aliases in aggregate functions of criteria queries

  1. Amit Jain says:

    Thanks it helped!

  2. Nita says:

    Good idea.There are many ways to skin a cat. Here’s another one that’s good for wrciladd queries ( %’). Of course you should validate the data first.def user_params = ‘slug’, ‘category’ def articles = Article.withCriteria for e in params if e.key in user_params ilike e.key, ‘%’ + e.value + ‘%’

Leave a Reply

Your email address will not be published. Required fields are marked *

+ 29 = 32

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>