Grails 2.5.0 - 快速查找域集合中的项目

Grails 2.5.0 - Fast lookup of items in collection over a domain

我有以下用于通过网络应用程序发送内部消息的代码:

域:

class Mail {
    ...
    User from
    static hasMany = [to: User]
    ...
}

我想做的是让登录并在 "to" 字段中找到地址的用户能够查看所有发给他们的邮件。使用 "from" 字段很容易做到这一点:

def totalMails = Mail.countByFrom(user)
...
def mails = Mail.findAllByFrom(user, [max: rows, offset: offset])

使用 "to" 字段执行此操作更加困难,我不确定如何执行此操作并加快查找速度。

您可以使用 criteria、where 或 HQL 查询。 HQL 查询将使您了解条件如何以及查询在数据库级别的工作位置。

条件

def totalMails = Mail.createCriteria().get {
    to {
        eq('id', user.id)
    }

    projections {
        count('id')
    }
}

def mails = Mail.createCriteria().list(max: rows, offset: offset) {
    to {
        eq('id', user.id)
    }
}

在哪里

def totalMails = Mail.where {
    to.id == user.id
}.count()

def mails = Mail.where {
    to.id == user.id
}.list(max: rows, offset: offset)

HQL

def totalMails = Mail.executeQuery 'select count(m) from Mail as m inner join m.to as t where t.id = :id', [id: user.id]

def mails = Mail.executeQuery 'select m from Mail as m inner join m.to as t where t.id = :id', [id: user.id], [max: rows, offset: offset]