Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 416
Igor Avatar asked Oct 14 '25 19:10

Igor


1 Answers

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.

like image 124
dmahapatro Avatar answered Oct 19 '25 13:10

dmahapatro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!