【发布时间】:2011-01-06 12:21:17
【问题描述】:
是否可以将原生 SQL 查询的结果映射到 Grails 域类实例的集合?
【问题讨论】:
是否可以将原生 SQL 查询的结果映射到 Grails 域类实例的集合?
【问题讨论】:
import com.acme.domain.*
def sessionFactory
sessionFactory = ctx.sessionFactory // this only necessary if your are working with the Grails console/shell
def session = sessionFactory.currentSession
def query = session.createSQLQuery("select f.* from Foo where f.id = :filter)) order by f.name");
query.addEntity(com.acme.domain.Foo.class); // this defines the result type of the query
query.setInteger("filter", 88);
query.list()*.name;
【讨论】:
def sessionFactory 必须出现在控件中(如果您在像我这样的控制器中执行此操作)。该字段被注入,然后你可以做 sessionFactory.currentSession.
或者在 Grails 应用程序中使用 Groovy SQL
import groovy.sql.Sql
class TestQService{
def dataSource //Auto Injected
def getBanksForId(int bankid){
def sql = Sql.newInstance(dataSource)
def rows = sql.rows(""" Select BnkCode , BnkName from Bank where BnkId = ?""" , [bankid])
rows.collect{
new Bank(it)
}
}
class Bank{
String BnkCode
String BnkName
}
}
【讨论】:
您可以自己映射它而不会太麻烦。或者如果使用HQL,您可以使用select new map(),然后使用query.list().collect { new MyDomainObject(it) }手动绑定参数。
【讨论】: