带条件的 Grails 查询:如何获取带列的映射?

发布于 2025-01-03 00:44:19 字数 496 浏览 2 评论 0原文

是否可以使用条件查询 grails 并接收映射列表而不是列表列表?我希望在结果中包含列名称,以便使用“关联数组”而不是数字数组偏移量。我目前正在执行类似

    def topFiveUsers = BlogEntry.createCriteria().list {
        projections {
            count('id')
            groupProperty('author')
        }
        maxResults 5
    }

Which results in [[123, app.User:1][111, app.User:2][...]...] 的操作,即列表列表。我宁愿想要类似 [[posts:123,author:app.User:1][posts:111,author app.User:2][...]...] 的内容。

一如既往:非常感谢您的帮助!

Is it possible, to query grails with criteria and receive a list of maps instead of a list of lists? I would like to have the column names in the results in order to then work with an 'associative array' rather then numeric array offsets. I currently do something like

    def topFiveUsers = BlogEntry.createCriteria().list {
        projections {
            count('id')
            groupProperty('author')
        }
        maxResults 5
    }

Which results in [[123, app.User:1][111, app.User:2][...]...], i.e. a list of lists. I would rather want something like [[posts:123, author: app.User:1][posts: 111, author app.User:2][...]...].

As always: help is highly appreciated!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

橘味果▽酱 2025-01-10 00:44:19

使用 resultTransformer()
作为参数,使用 CriteriaSpecification.ALIAS_TO_ENTITY_MAP
关于该主题的文档和示例很少。但这里有一个例子:

import org.hibernate.criterion.CriteriaSpecification

BlogEntry.withCriteria {
  maxResults 5
  resultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP)
  projections {
    count('id', 'total')
    groupProperty('author', 'author')
  }      
}  

请注意,所有投影都需要别名。否则,生成的映射由空值组成。

Use resultTransformer().
As the parameter use CriteriaSpecification.ALIAS_TO_ENTITY_MAP
The documentation and examples on this topic is scarce. But here's an example:

import org.hibernate.criterion.CriteriaSpecification

BlogEntry.withCriteria {
  maxResults 5
  resultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP)
  projections {
    count('id', 'total')
    groupProperty('author', 'author')
  }      
}  

Note that alias is required for all projections. Otherwise, the resulting map consists of nulls.

画离情绘悲伤 2025-01-10 00:44:19
def topFiveList = []
topFiveUsers.each { rec ->
    topFiveList << [posts: rec[0], author: rec[1]]
}
def topFiveList = []
topFiveUsers.each { rec ->
    topFiveList << [posts: rec[0], author: rec[1]]
}
野の 2025-01-10 00:44:19
def converted = topFiveUsers.collect{ [posts: it[0], author: it[1]] }
def converted = topFiveUsers.collect{ [posts: it[0], author: it[1]] }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文