5

@SqlResultSetMapping アノテーションと同様に、ネイティブ SQL クエリの結果を Grails の単純な Bean にマップしたいと考えています。

たとえば、クエリが与えられた場合

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

結果をマップする

class FooBarBaz {
  String foo
  String bar
  String baz
}

grailsでこれを行う方法の例を誰か提供できますか? 前もって感謝します。

4

1 に答える 1

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)}
于 2010-03-12T16:55:16.290 に答える