[英]Grails: how to programatically bind command object data to domain object in service?
I have a command object that I want to convert into a domain object. 我有一个命令对象,我想转换为域对象。
However, the object I want to convert the command object into may be one of two domain classes (they're both derived classes), and I need to do it in a service (which is where, based on other data, I decide which type of object it should be bound to). 但是,我想将命令对象转换为的对象可能是两个域类之一(它们都是派生类),我需要在服务中执行它(根据其他数据,我决定哪个应该绑定的对象类型)。 Is this possible and what's the best way to do this?
这是可能的,这是最好的方法吗?
bindData()
only exists in a controller. bindData()
仅存在于控制器中。
Do I just have to manually map command object parameters to the appropriate domain object properties? 我是否只需手动将命令对象参数映射到适当的域对象属性? Or is there a faster/better way?
还是有更快/更好的方式?
If the parameters have the same name, then you can use this question to copy the values over. 如果参数具有相同的名称,则可以使用此问题复制值。 A quick summary can be as follows.
快速摘要如下。
Using the Grails API 使用Grails API
You can cycle through the properties in a class by accessing the properties
field in the class. 您可以通过访问类中的
properties
字段来遍历类中的properties
。
object.properties.each { property ->
// Do something
}
You can then check to see if the property is present in the other object. 然后,您可以检查该属性是否存在于另一个对象中。
if(otherObject.hasProperty(property) && !(key in ['class', 'metaClass']))
Then you can copy it from one object to the other. 然后,您可以将其从一个对象复制到另一个对象。
Using Commons 使用Commons
Spring has a really good utility class called BeanUtils
that provides a generic copy method that means you can do a simlple oneliner. Spring有一个非常好的实用程序类,名为
BeanUtils
,它提供了一个通用的复制方法,这意味着你可以做一个简单的oneliner。
BeanUtils.copyProperties(object, otherObject);
That will copy values over where the name is the same. 这会将值复制到名称相同的位置。 You can check out the docs here .
你可以在这里查看文档。
Otherwise.. 除此以外..
If there is no mapping between them, then you're kind of stuck because the engine has no idea how to compare them, so you'll need to do it manually. 如果它们之间没有映射,那么你就会陷入困境,因为引擎根本不知道如何比较它们,所以你需要手动完成它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.