我想将本机SQL查询的结果映射到grails中的简单bean,类似于@SqlResultSetMapping注释所做的.
例如,给定一个查询
从//等选择x.foo,y.bar,z.baz …
将结果映射到
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)}