Search code examples
grailsgroovycreatecriteria

I am facing a problem with projections in createCriteria


I am facing a problem to get the required result from this closure

def authors{
    results = Message.createCriteria().list {
        projections {
            author{
                groupProperty('id', 'authorId') // 2nd param is alias
                property('username', 'username')
            }
        }

        and{
            ...
            ...
        }
    }

    [authors:results]
}

I want to show this list on my gsp page and wants to access the values using aliases (while above criteria is returning a list of arrays)


Solution

  • Use resultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP).

    import org.hibernate.criterion.CriteriaSpecification
    Message.createCriteria().list {
        resultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP)
        projections {
            author{
                groupProperty('id', 'authorId')
                property('username', 'username')
            }
        }
    }
    

    All projections must have aliases. Otherwise the resulting map will contain nulls.