将本机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;
答
你可以映射它自己没有太多的麻烦。或者,如果使用HQL,则可以使用select new map()
,然后以query.list().collect { new MyDomainObject(it) }
手动绑定参数。
+0
确实如此,但我认为这会比Hibernate经过大量优化的代码慢得多。 – 2010-01-20 01:28:23
答
或者使用Groovy SQL在Grails的应用
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
}
}
+0
Sql.newInstance(dataSource)失败,因为没有采用datasourc对象的方法。 – benstpierre 2013-09-13 22:58:54
,这是非常有益的! – Topera 2011-05-17 21:44:16
谢谢。它也帮助了我...... – 2011-09-14 06:07:14
在这个答案中我缺少的是'def sessionFactory'必须出现在控件中(如果你是在像我这样的控制器中执行此操作)。该字段被注入,然后您可以执行sessionFactory.currentSession。 – Jason 2015-06-24 16:23:15