默认值/常量⭐️

  • 默认值/常量都是使用String值表达的. 会调用相应的类型转换方法转换成对应的target类型并赋值.
  • 默认值/DefaultValue:
    • 当source属性为null时, 可以将target属性设轩为defaultValue
  • 常量/Constant:

    • 可以给target属性设计常量值.
    • 使用常量值时, 不允许在mapping中再引用source属性.


    例: Mapping方法使用默认值/常量

  1. @Mapper(uses = StringListMapper.class)
  2. public interface SourceTargetMapper {
  3. SourceTargetMapper INSTANCE = Mappers.getMapper( SourceTargetMapper.class );
  4. @Mapping(target = "stringProperty", source = "stringProp", defaultValue ="undefined")
  5. @Mapping(target = "longProperty", source = "longProp", defaultValue = "-1")
  6. @Mapping(target = "stringConstant", constant = "Constant Value")
  7. @Mapping(target = "longWrapperConstant", constant = "3001")
  8. @Mapping(target = "dateConstant", dateFormat = "dd-MM-yyyy", constant = "09-01-2014")
  9. @Mapping(target = "stringListConstants", constant = "jack-jill-tom") //会调用StringListMapper.class中的方法.
  10. Target sourceToTarget(Source s);
  11. }

表达式/Expression⭐️

通过表达式可以调用一些语言构造. 目前只支持java语言 这个特性很有用, 比如调用构造函数. 可以在表达式中使用整个source对象, 而不是仅仅source里面的属性.

例子:

  1. imports org.sample.TimeAndFormat;
  2. @Mapper( imports = TimeAndFormat.class ) //通过imports来引用类, 这样可以在expression中直接使用简单类名, 而不用写全限定类名.
  3. public interface SourceTargetMapper {
  4. SourceTargetMapper INSTANCE = Mappers.getMapper( SourceTargetMapper.class );
  5. @Mapping(target = "timeAndFormat",
  6. expression = "java( new TimeAndFormat( s.getTime(), s.getFormat() ))")
  7. Target sourceToTarget(Source s);
  8. }