views:

270

answers:

1

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.

+1  A: 

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)}
Don