2012-06-21 78 views
1

ORDER BY我有這樣的關係:如何Grails的HQL語句

class Foo { 
    static hasMany = [bars: Bar, things: Thing] 
} 

class Bar { 
    // Has nothing to tie it back to Foo or Thing 
} 

class Thing { 
    // Has nothing to tie it back to Foo or Bar 
} 

enter image description here

我有下列參數,其中大部分是用於與flexigrid分頁下面的查詢。該查詢通過Foo獲取與Bar的特定實例關聯的所有Thing實例。所以,如果我的Bar實例是Bar1會期望我的查詢返回Thing1Thing2

def obj = Bar.get(1) // Get Bar1 
def max = params.int("max") ?: 100 // Default max returned results is 100 unless otherwise specified 
def offset = params.int("offset") ?: 0 // Default offset is 0 unless otherwise specified 
def sortname = params.sortname ?: "id" // Default is id, but could be any member of Thing that is not a "hasMany" 
def sortorder = params.sortorder ?: "ASC" // Default is ASC, but could be DESC 

def namedParams = [ obj: obj, max: max, offset: offset ] 

Thing.executeQuery("SELECT DISTINCT f.things FROM Foo f INNER JOIN f.things things INNER JOIN f.bars bars WHERE bars =:obj ORDER BY ${sortname} ${sortorder}", namedParams) 

休眠不允許命名參數的使用指定ORDER BY條款,所以我只是插入的字符串。問題在於結果不按我指定的順序排列。當使用ORDER BY id Grails告訴我id是不明確的。

知道變量sortname將始終是Thing的成員,我如何指定要排序的內容?

一些我已經試過的東西:

ORDER BY Thing.id // Fail 
ORDER BY f.things.id // Fail 
ORDER BY things.id // FAIL! 

回答

2

查詢應該是:

SELECT DISTINCT thing FROM Foo f 
INNER JOIN f.things thing 
INNER JOIN f.bars bar 
WHERE bar = :obj 
ORDER BY thing.id 

即你應該使用實體的別名SELECT子句,而不是它的路徑中,並在order by子句中使用相同的別名。

+0

太棒了!感謝你的幫助。 HQL並不是一個與SQL有很大差異的地方,但它足以導致我一些問題。雖然我現在抓住了它,但:) – ubiquibacon