解决标准生成器中缺少sqlProjection支持的问题?

时间:2011-08-11 15:25:53

标签: hibernate grails gorm

http://jira.grails.org/browse/GRAILS-2803表示缺乏对sqlProjection的支持。它作为副本关闭,据说在Grails v1.2中修复。但是“重复”问题涉及sqlRestriction,我不相信sqlProjection至少已经实现了Grails v1.3.2。

在critera中使用sqlProjection是否有任何变通方法?例如,

def results = Report.createCriteria() list {
            projections {
                sum('correctResponses')
                sum('allResponses')

                sqlProjection("(sum(correct_responses) / sum(all_responses))", ["grade"] as String[], [Hibernate.INTEGER] as Type[])
                groupProperty('name')
            }
            and {
                if (startDate)
                    ge("date", startDate)

                if (endDate)
                    lt("date", endDate + 1) //add one day so search is inclusive of end date

                'in' ("id", ids)
            }
            order(orderColumn ?: 'name', orderDirection ?: 'asc')
        }

1 个答案:

答案 0 :(得分:5)

我遇到了类似的问题,并在另一个问题的答案中找到了解决方案。

您可以使用addProjectionToList()方法解决此问题。请看下面的答案中的“选项2”作为示例:

https://stackoverflow.com/a/7652787

此特定示例的标准DSL如下:

def results = Report.createCriteria().list {
    projections {
        sum('correctResponses')
        sum('allResponses')

        addProjectionToList(Projections.sqlProjection(
            '(sum(correct_responses) / sum(all_responses)) as grade',
            ['grade'] as String[],
            [Hibernate.INTEGER] as Type[]
        ), 'sumProjection')
        groupProperty('name')
    }
    and {
        if (startDate)
            ge("date", startDate)

        if (endDate)
            lt("date", endDate + 1) //add one day so search is inclusive of end date

        'in'("id", ids)
    }
    order(orderColumn ?: 'name', orderDirection ?: 'asc')
}