默认值/常量⭐️
- 默认值/常量都是使用String值表达的. 会调用相应的类型转换方法转换成对应的target类型并赋值.
- 默认值/DefaultValue:
- 当source属性为null时, 可以将target属性设轩为defaultValue
常量/Constant:
- 可以给target属性设计常量值.
- 使用常量值时, 不允许在mapping中再引用source属性.
例: Mapping方法使用默认值/常量
@Mapper(uses = StringListMapper.class)
public interface SourceTargetMapper {
SourceTargetMapper INSTANCE = Mappers.getMapper( SourceTargetMapper.class );
@Mapping(target = "stringProperty", source = "stringProp", defaultValue ="undefined")
@Mapping(target = "longProperty", source = "longProp", defaultValue = "-1")
@Mapping(target = "stringConstant", constant = "Constant Value")
@Mapping(target = "longWrapperConstant", constant = "3001")
@Mapping(target = "dateConstant", dateFormat = "dd-MM-yyyy", constant = "09-01-2014")
@Mapping(target = "stringListConstants", constant = "jack-jill-tom") //会调用StringListMapper.class中的方法.
Target sourceToTarget(Source s);
}
表达式/Expression⭐️
通过表达式可以调用一些语言构造. 目前只支持java语言 这个特性很有用, 比如调用构造函数. 可以在表达式中使用整个source对象, 而不是仅仅source里面的属性.
例子:
imports org.sample.TimeAndFormat;
@Mapper( imports = TimeAndFormat.class ) //通过imports来引用类, 这样可以在expression中直接使用简单类名, 而不用写全限定类名.
public interface SourceTargetMapper {
SourceTargetMapper INSTANCE = Mappers.getMapper( SourceTargetMapper.class );
@Mapping(target = "timeAndFormat",
expression = "java( new TimeAndFormat( s.getTime(), s.getFormat() ))")
Target sourceToTarget(Source s);
}