我有一张这样的 map :['var1':'property1',
'var2':'3']
和这样的类(class):
class MyClass{
MyEnum var1
int var2
String var3
}
enum MyEnum{
PROP1( "property1" )
PROP2( "property2" );
private final String variable;
public MyEnum( String variable ){ this.variable = variable }
public String getVariable(){ return variable }
}
我想尝试绑定(bind)
var1
和 var2
到一些现有的对象上来获得验证,但我该怎么做呢?
最佳答案
您可以使用 bindData
在 Controller 内部。此方法具有可选参数,允许您显式声明绑定(bind)应包含或排除哪些属性,例如
def map = ['var1':'property1', 'var2':'3']
def target = new MyClass()
// using inclusive map
bindData(target, map, [include:['var1', 'var2']])
// using exclusive map
bindData(target, this.params, [exclude:['var2']])
如果您想在 Controller 外部进行这种绑定(bind),请使用
org.codehaus.groovy.grails.web.binding.DataBindingUtils
的方法之一。 ,例如/**
* Binds the given source object to the given target object performing type conversion if necessary
*
* @param object The object to bind to
* @param source The source object
* @param include The list of properties to include
* @param exclude The list of properties to exclud
* @param filter The prefix to filter by
*
* @return A BindingResult or null if it wasn't successful
*/
public static BindingResult bindObjectToInstance(Object object, Object source, List include, List exclude, String filter)
这是使用此方法执行与
bindData
的“包含映射”调用相同的绑定(bind)的示例。多于def map = ['var1':'property1', 'var2':'3']
def target = new MyClass()
DataBindingUtils.bindObjectToInstance(target, map, ['var1', 'var2'], [], null)
关于hibernate - 仅将一些属性绑定(bind)到 grails 域对象上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5806478/