Grails: how to programmatically bind command object data to a domain object in a service?

I have a command object that I want to convert to a domain object.

However, the object I want to convert the command object to can be one of the two domain classes (they are both derived classes) and I need to do this in the service (which is where, based on other data, I decide to which type object, it must bind). Is this possible and what's the best way to do it? bindData()

exists only in the controller.

Do I need to manually map the parameters of the command object to the corresponding properties of the domain object? Or is there a faster / better way?

+3


source to share


1 answer


If the parameters have the same name, you can use this question to copy the values. The summary could be as follows.

Using the Grails API

You can loop over properties in a class by accessing a field properties

in the class.

object.properties.each { property -> 
    // Do something
}

      

Then you can check if the property is present in another object.

if(otherObject.hasProperty(property) && !(key in ['class', 'metaClass']))

      

Then you can copy it from one object to another.



Using Commons

Spring has a really nice utility class called BeanUtils

, which provides a generic copy method, which means you can do simlple oneliner.

BeanUtils.copyProperties(object, otherObject);

      

This will copy the values ​​where the name is the same. You can check the docs here .

Otherwise..

If there is no mapping between them, then you are stuck because the engine doesn't know how to compare them, so you will need to do it manually.

+6


source







All Articles