5
votes

I have a User class that hasMany = [friends:User]

Now I am trying to display the friends list - ${user.friends}

However, I'd like to be able to apply parameters like I can with, for example, User.findAllBy(user, [max:10, sort: 'dateCreated', order: 'desc"])

Can someone kindly tell me how to do this on a one-to-many in Grails / Groovy ?

2

2 Answers

3
votes

I'd use HQL:

String hql = '''
select u from User u, User u2
where u in elements(u2.friends) and u2=:user
order by u.dateCreated desc
'''
int max = ...
int offset = ...
def friends = User.executeQuery(hql, [user: user], [max: max, offset: offset])

You could try to filter the friends collection, but as soon as you do anything with it it'll get fully loaded from the database, so if you only want 10 instances you'll have wasted loading all of the rest.

0
votes

I just came across the GORM Labs plugin for Grails and it offers the following functionality

"For every "hasMany" property, there is now an associated method that takes pagination properties ("offset" and "max") and produces the appropriate page. There is also a "countBars" instance property that will provide the total size of the "bars" collection. This is all done with a separate database query if the collection has not been initialized previously, so you can avoid loading all the elements of the collection"

http://www.grails.org/plugin/gorm-labs