Igor
Igor

Reputation: 1464

Is there any way to return a Map with some fields from a createCriteria in Grails?

I have an object where I need to query and return it as a Map, but I don't want to iterate over the object again as I'm already doing a query and it can get a bad performance.

List<MyObject> myObjectList = MyObject.createCriteria().list(params) {
...
}

But what I need is a Map like:

myObjectList.each { MyObjectList myObject ->
   myMap.add([person: myObject.person, myObject: myObject, listIntoObject: myObject.listInsideObject as List])
}

I found another way to get a map like this but it still not the better way to get a Map from a List that I'm querying with GORM...

myMap = myObjectList.collect{ [person: it.person, myObject: it, listIntoObject : it.invoiceDetails as List] }

Is there a better way to get a Map using GORM?

Upvotes: 4

Views: 3178

Answers (2)

victorf
victorf

Reputation: 1048

You can use import org.hibernate.criterion.CriteriaSpecification with withCriteria() to transform the result in a Collection object, with properties chosen by you only:

import org.hibernate.criterion.CriteriaSpecification

def criteria = User.withCriteria(){
    resultTransformer CriteriaSpecification.ALIAS_TO_ENTITY_MAP
    createAlias 'personalData', 'p'
    eq 'id', params.id
    // ...and so on, then
    projections {
        property 'id', 'myId' // a property called 'myId', from User
        property 'p.name', 'userName' // from personalData, a property mapped by a fk in User
        property 'p.age', 'age'
    }
}

Upvotes: 0

dmahapatro
dmahapatro

Reputation: 50245

You can use org.hibernate.transform.Transformers to transform the result to an entity map

import org.hibernate.transform.Transformers

def criteria = MyObject.createCriteria()
criteria.resultTransformer(Transformers.ALIAS_TO_ENTITY_MAP)

def myObjectList = criteria.list(params) {
    ...
}

You can also fall back to HQL as well. Refer the UPDATE section of a similar answer for more details.

Upvotes: 2

Related Questions