grails - Grails/GORM 中的结果集映射

标签 grails jpa groovy grails-orm sqlresultsetmapping

我想将原生 SQL 查询的结果映射到 grails 中的一个简单 bean,类似于 @SqlResultSetMapping 注释所做的。

例如,给定一个查询
select x.foo, y.bar, z.baz from //etc...
将结果映射到

class FooBarBaz {
  String foo
  String bar
  String baz
}

谁能提供一个如何在 grails 中执行此操作的示例?
提前致谢。

最佳答案

我在 Grails 控制台中成功测试了这个

import groovy.sql.Sql

class FooBarBaz {
  String foo
  String bar
  String baz
}

// Initialising the Sql object like this ensures that the SQL statement
// will participate in the current transaction (if one exists)          
// 'ctx' refers to the Spring ApplicationContext when using the Grails console  
def sessionFactory = ctx.getBean('sessionFactory')
Sql sql = new Sql(sessionFactory.currentSession.connection())

def query = 'select email, user_real_name, phone from user'
def results = []
sql.eachRow query, {row -> results << new FooBarBaz(foo: row.email, bar: row.user_real_name, baz: row.phone)}

关于grails - Grails/GORM 中的结果集映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2431282/

相关文章:

grails - 动态调度作业:在Groovy中使用cron触发器

grails - Grails 2.4.4 Criteria query issue,没有这样的属性:Criteria类的规范:grails.orm.HibernateCriteriaBuilder

即使定义了变量,Jenkins 管道也会为后期阶段提供 "No such property"

java - 当我尝试插入通知类型对象时,子实体也会尝试插入

java - 通过 Spock 测试应用参数约束

mongodb - Mongodb:如何按对象列表分组

Grails 1.3.7 spring security - 启动时未找到线程绑定(bind)请求

grails - grails 3.2 rest api,新记录未列出

java - JPA : not overriding equals() and hashCode() in the entities?

sql - 类型安全查询的确切含义是什么?