【问题标题】:How to ORDER BY in Grails HQL statement如何在 Grails HQL 语句中排序
【发布时间】:2012-06-21 23:22:25
【问题描述】:

我有这样的关系:

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
}

我有以下带有以下参数的查询,其中大部分用于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 )

Hibernate 不允许使用命名参数来指定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!

【问题讨论】:

    标签: hibernate grails sql-order-by hql


    【解决方案1】:

    查询应该是:

    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 子句中使用相同的别名。

    【讨论】:

    • 太棒了!感谢你的帮助。 HQL 与 SQL 并没有太大的不同,但它的不同足以引起我的一些问题。不过,我现在已经掌握了它:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-03
    • 1970-01-01
    • 1970-01-01
    • 2011-02-03
    • 1970-01-01
    • 1970-01-01
    • 2013-11-12
    相关资源
    最近更新 更多