Count one-to-one relationship in grails

ⅰ亾dé卋堺 提交于 2019-12-02 09:11:01

The trick is to do a group by on the code and a count() on the user. You can do this using either HQL or a criteria query.

HQL

Here's an example in HQL:

VoiceUser.executeQuery('SELECT licence.code, COUNT(user) FROM VoiceUser AS user INNER JOIN user.licenceType AS licence GROUP BY licence.code')

If you're familiar with SQL, most of this should make sense right away. An important difference is the syntax for joining domain classes. HQL deals with domain classes, not tables.

Criteria query

And here's the equivalent criteria query.

VoiceUser.withCriteria {
    projections {        
        licenceType {
            groupProperty('code')
        }

        count('id')
    }
}

Alternative queries

The queries shown above return a List<List> like this:

[
    ['A', 2], 
    ['B', 2], 
    ['C', 0]
]

If you provide a LicenceType (or its code) as input to the query, then you can get the count for just that LicenceType. For instance, here are examples which retrieve the user count for licence code 'A'.

HQL

def result = VoiceUser.executeQuery('SELECT COUNT(user) FROM VoiceUser AS user INNER JOIN user.licenceType AS licence WHERE licence.code = :code', [code: 'A'])[0]

Criteria query

def result = VoiceUser.createCriteria().get {
    licenceType {
        eq('code', 'A')
    }

    projections {        
        count('id')
    }
}

Additional resources

I've got a series of articles which explain HQL, criteria, and where queries in detail; such as how to use projections and joins. Feel free to check them out.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!