I want to map the result of a native SQL query to a simple bean in grails, similar to what the @SqlResultSetMapping annotation does.
For example, given a query
select x.foo, y.bar, z.baz from //etc...
map the result to
class FooBarBaz {
String foo
String bar
String baz
}
Can anyone provide an example of how to do this in grails? Thanks in advance.
I tested this successfully in the Grails console
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)}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.