2010-01-18 58 views

回答

18
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; 
+0

,這是非常有益的! – Topera 2011-05-17 21:44:16

+0

謝謝。它也幫助了我...... – 2011-09-14 06:07:14

+0

在這個答案中我缺少的是'def sessionFactory'必須出現在控件中(如果你是在像我這樣的控制器中執行此操作)。該字段被注入,然後您可以執行sessionFactory.currentSession。 – Jason 2015-06-24 16:23:15

2

你可以映射它自己沒有太多的麻煩。或者,如果使用HQL,則可以使用select new map(),然後以query.list().collect { new MyDomainObject(it) }手動綁定參數。

+0

確實如此,但我認爲這會比Hibernate經過大量優化的代碼慢得多。 – 2010-01-20 01:28:23

8

或者使用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

相關問題