2012-06-05 24 views
1

我測試了控制器和簡單的渲染JSON要檢索的JSON。然而,我注意到,該控制器返回的數據,但它不與鍵/值對正常返回JSON。它從字面上只返回數據。但是我注意到,如果我使用Incident.getAll(),它會正確返回JSON。例如,它會返回[INCIDENTID:「值」],而不是使用executreQuery剛剛返回數據。的Grails:使用的executeQuery

我的代碼:

def incident = Incident.executeQuery("select a.INCIDENTID from Incident a") 
render incident as JSON 

回答

2

executeQuery結果是你所指定的屬性,而不是實際的域對象的列表。例如:

TestDomain.executeQuery("select t.id from TestDomain") as JSON 
===> [1, 2, 3] 

如果你想域對象,你可以使用findAll代替。嘗試是這樣的:

TestDomain.findAll("from TestDomain") as JSON 
===>[{"class":"TestDomain","id":1,"name":"one"}, 
    {"class":"TestDomain","id":2,"name":"two"}, 
    {"class":"TestDomain","id":3,"name":"three"}] 
+0

啊。這使事情更清楚。所以,如果我的標準增加的findAll(),將它還是回到了我所有的域對象相匹配的標準是什麼? –

+0

正確的,如果你添加一個where子句它仍然會返回域對象。 – ataylor

+0

你也可以使用Hibernate Criteria API定義一個命名查詢,這允許更復雜的查詢創建http://grails.org/doc/latest/ref/Domain%20Classes/namedQueries.html – dbrin