Grails 3.3 GORM CriteriaBuilder 属性函数

Grails 3.3 GORM CriteriaBuilder functions on properties

这些天,我使用 Grails 3.3 和 GORM CriteriaBuilder 进行大部分查询,但我对如何调用属性上的函数一筹莫展——例如,在日期上调用 hour() 函数 属性 .如果我使用 where DetachedCriteria 我可以有这样的东西:

def whereQuery = Student.where {
    hour(registration) = 15
}

查找在 15:00 和 15:59 之间注册的所有学生。

但是,如果我改为使用 CriteriaBuilder,我将无法执行此操作:

def c = Student.createCriteria()
def results =  c.list {
    eq 'hour(registration)', 15
}

有什么方法可以在构建器 DSL 中完成此操作吗?我知道我可以回到域 class 并定义一个从日期字段中提取小时的映射,但这看起来有点笨拙。

试试sqlRestriction

def results = Student.withCriteria {
    sqlRestriction 'hour(registration) = 15'
}

参见 http://gorm.grails.org/latest/hibernate/manual/index.html#criteria

中的 7.5.6. Using SQL Restrictions