Grails createCriteria group by (groupProperty function) multiple attributes

kuceram picture kuceram · Aug 23, 2011 · Viewed 10.9k times · Source

I'm wondering if grails createCriteria supports group by multiple attributes like pure sql does. I'd like to list entries like this:

def criteria = DomainClass.createCriteria()
def results = criteria.list {
    groupProperty('parameterA')
    groupProperty('parameterB')
}

This will list just entries with unique parameterA and parameterB combination. The problem is that this doesn't work, is there any solution or should I use hsql or something simmilar?

Thanks, Mateo

Answer

Sr. Oshiro picture Sr. Oshiro · Oct 21, 2012

Try to put projections, eg.:

def criteria = DomainClass.createCriteria()
def results = criteria.list {
    projections{
        groupProperty('parameterA')
        groupProperty('parameterB')
    }
}

I wrote some tests

void test2xGroupProperty(){
    def pablo = new Artist(name: 'Pablo').save()
    def salvador = new Artist(name: 'Salvador').save()
    new Portrait(artist: pablo, name: "Les Demoiselles d'Avignon 1", value: 10.00).save()
    new Portrait(artist: pablo, name: "Les Demoiselles d'Avignon 2", value: 10.00).save()
    new Portrait(artist: pablo, name: "Les Demoiselles d'Avignon 3", value: 10.00).save()
    new Portrait(artist: salvador, name: "The Persistence of Memory 1", value: 20.00).save()
    new Portrait(artist: salvador, name: "The Persistence of Memory 2", value: 20.00).save()
    new Portrait(artist: salvador, name: "The Persistence of Memory 3", value: 20.00).save()
    def artistValue = Portrait.withCriteria{
        projections{
            groupProperty('value')
            groupProperty('artist')
        }
    }
    assert [[10.00, pablo], [20.00, salvador]] ==  artistValue
}

See more samples here: https://github.com/fabiooshiro/plastic-criteria/blob/master/src/groovy/plastic/criteria/CriteriaDocTests.groovy