grails - 在createCriteria上使用属性时可以作为对象返回吗?

标签 grails

为什么在property()上使用createCriteria时会返回列表而不是对象?如果不把property()给我整个对象而不是列表? [[1, 'John', 'Tusk'],[2, 'Nila','Hans'],...]

def employees = User.createCriteria().list{
    ...
    projections{
        property("id")
        property("pd.firstName")
        property("pd.lastName")
    } 
}
def results = []
employees.each{
    results <<  [id: it[0], name: it[1] + " " + it[2]]
}

除了使用employees.each之外,还有另一种方法可以像这样将其呈现为JSON:
[{"id":10,"name":"Erik Tucker"},{"id":83,"name":"Jimmy Sun"},..]

最佳答案

原因在文档本身内。

A projection is used to change the nature of the results.



使用投影时,结果变成listlist,其中包含投影属性的值,而不是匹配对象实例的列表。这是设计使然,是documented

使用each的方法是完全可以接受的。虽然如此,我个人会使用collect,但结果是相同的。

关于grails - 在createCriteria上使用属性时可以作为对象返回吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30357815/

相关文章:

grails - 如何更改默认的Grails/GORM查找?

grails - 使用本地平面文件存储库而不是远程 Maven 存储库

hibernate - Grails上的GORM save()未保存在数据库中

rest - Grails Spring Security REST 插件 - token 存储失败

spring - 在 Grails 中使用 HazelCast 进行 Web session 复制 - HazelcastSerializationException

jquery - jQuery和AJAX仅发送值的第一行

Grails:鸭子类型(duck typing)和多对多集合类

grails - 与messages.properties的参数有关的问题,除零以外的所有数字均可正常工作

sql-server - 使用SQL Server在grails上映射map数据类型

grails - Grails Datepicker