Grails, gorm technologies

Pagination and sorting in many-to-many relationship

This example shows how to use pagination and sorting with many-to-many relationship in Grails.

Suppose you have two domain classes: Author, Article and you want to display all articles of some author in a page with pagination.

Domain classes:

1
2
3
4
5
6
7
class Author {
    static hasMany = [articles: Article]
}
class Article {
    belongsTo = Author
    static hasMany = [authors: Author]
}
The HQL query with pagination parameters:

1
2
3
def author = Author.get(id)
Article.findAll("FROM Article  WHERE :author IN ELEMENTS(article.authors)",[author:author],
    [max:params.max, offset:params.offset])
For sorting you can use order by:

1
2
3
Article.findAll("FROM Article article  WHERE :author IN ELEMENTS(article.authors)" +
                (params.sort && params.order ? "order by article.${params.sort} ${params.order}" : ''),
                [author: author, max:params.max, offset:params.offset])

Hope this would be helpful!

Looking to hire a software engineer?
Don't hesitate to contact us.

Comments