我想将本机SQL查询的结果映射到grails中的简单bean,类似于@SqlResultSetMapping批注所做的。
例如,给定查询
select x.foo, y.bar, z.baz from //etc...
将结果映射到
class FooBarBaz {
String foo
String bar
String baz
}
任何人都可以提供一个如何在grails中执行此操作的示例吗? 提前谢谢。
答案 0 :(得分:2)
我在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)}