Grails/GORM 中的结果集映射

arm*_*ino 5 grails groovy jpa grails-orm sqlresultsetmapping

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

例如,给定一个查询

select x.foo, y.bar, z.baz from //etc...

将结果映射到

class FooBarBaz {
  String foo
  String bar
  String baz
}
Run Code Online (Sandbox Code Playgroud)

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

Dón*_*nal 3

我在 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)}
Run Code Online (Sandbox Code Playgroud)