集合分页

Pagination with collection

我有像

这样的自我引用域
User{

 static hasMany=[friends:User]

}

我可以这样获取一个用户的所有好友:

user.friends

但是我需要在我所在的地方应用分页 运行 不知道,有什么建议吗?

您可以使用条件来检索您的用户对象。因此,您将能够使用分页:

int maxElementsPerPage = 15    
User.createCriteria().list(offset: currentPage * maxElementsPerPage, 
                           max: maxElementsPerPage) {
    // condition here
    'in' ('id', user.friends*.id) 
    // I'm not sure if you need to put '*.id'
} 

您只需增加 'currentPage' 即可获得下一页的元素。

对于 Grails 标准,您应该查看 official Grails criteria documentation

或者,您可以在 GSP 中使用 Grails 标签(它将处理所有事情):

<g:paginate controller="user" action="list" total="${userCount}" />

更多详情here

如果您的域 class 中有一个集合需要分页,您应该将其设为单向一对一:

class User {
  static belongsTo = [ friend:User ]
}

否则 GORM 将不得不缓存 hasMany 个 ID。

那么查询就很简单了:

def friends = User.findAllByFriend( user, [ max:100, offset:0 ] )