Search code examples
grailsgrails-ormgrails-2.0grails-domain-class

How to limit the Relation Elements of a Class in Grails?


I have

class User {
  String name

  hasMany = [books: Book]
}


class Book (
  String name
  belongsTo = [user: User]
}

Now, I can access all books of a user instance as:

def user = User.find("someId")
println user.books

How can I limit the number of books such that I get only the first x books from user.books? Is there also a way to sort them?


Solution

  • One viable approach is to define books as List inside User. You would need to have an index column but you could get the benefit of pagination and ordering like:

    class User{
        List books
        static hasMany = [books: Book]
    }
    
    def user = User.find("someId")
    println user.books?.getAt(3..10).sort{it.name}
    

    Note:-
    All books for User will be fetched lazily, using the above approach will filter books from index 3 till 10.

    In case you want to optimize the lazy fetch strategy (N + 1), then you would probably need to have a look at batchSize and order. Also sort as a side note.

    Example:

    class User {
      String name
      static hasMany = [books: Book]
      static mapping = {
          books batchSize: 10
      }
    }
    
    class Book (
      String name
      static belongsTo = [user: User]
      static mapping = {
          order "desc"
      }
    }