仅将一些属性绑定到grails域对象上?

Ste*_*all 0 validation grails groovy hibernate grails-orm

我有这样的地图:

['var1':'property1', 'var2':'3']

和这样的一个类:

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 }
}
Run Code Online (Sandbox Code Playgroud)

我想只是尝试绑定var1,并var2到一些现有的对象得到验证,但我要如何做到这一点?

Dón*_*nal 6

您可以bindData在控制器内部使用.此方法具有可选参数,允许您显式声明绑定应包含或排除哪些属性,例如

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']])
Run Code Online (Sandbox Code Playgroud)

如果你想在控制器外部进行这种绑定,请使用其中一种方法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) 
Run Code Online (Sandbox Code Playgroud)

下面是使用此方法来执行相同的结合为一体的"包容地图"的调用的例子bindData以上

def map = ['var1':'property1', 'var2':'3']
def target = new MyClass()
DataBindingUtils.bindObjectToInstance(target, map, ['var1', 'var2'], [], null)
Run Code Online (Sandbox Code Playgroud)