MapperStruct是一个非常好用的Bean映射工具,虽然还需要去维护一个接口来进行映射,但是其bean对象的映射却是非常的高效,另外它还提供了提供了许多自定义的配置,方便我们在各种场景下灵活使用!
如果目标对象与源对象属性不一致,则需要明确指定属性名
@Mapper
public interface CarMapper {
@Mapping(target = "manufacturer", source = "make")
@Mapping(target = "seatCount", source = "numberOfSeats")
CarDto carToCarDto(Car car);
@Mapping(target = "fullName", source = "name")
PersonDto personToPersonDto(Person person);
}
指定目标对象使用指定表达式赋值
@Mapping(target = "creationDate", expression = "java(new java.util.Date())")
如果复制对象内部有引用类型的成员,可自定义方法,完成引用类型之间的对应拷贝。
@Mapper
public interface CarMapper {
@Mapping(...)
...
CarDto carToCarDto(Car car);
default PersonDto personToPersonDto(Person person) {
//hand-written mapping logic
}
}
@Mapper
public interface AddressMapper {
@Mapping(target = "description", source = "person.description")
@Mapping(target = "houseNumber", source = "address.houseNo")
DeliveryAddressDto personAndAddressToDeliveryAddressDto(Person person, Address address);
}
@Mapper
public interface AddressMapper {
@Mapping(target = "description", source = "person.description")
@Mapping(target = "houseNumber", source = "hn")
DeliveryAddressDto personAndAddressToDeliveryAddressDto(Person person, Integer hn);
}
如果复制对象内部有相同的引用类型,指定成员属性名,可直接复制。如果不同,则需要明确指定成员变量的某个属性,对应另一个对象的某个成员属性的某个属性。
@Mapper
public interface CustomerMapper {
@Mapping( target = "name", source = "record.name" )
@Mapping( target = ".", source = "record" )
@Mapping( target = ".", source = "account" )
Customer customerDtoToCustomer(CustomerDto customerDto);
}
通过 @MappingTarget 注解,更新实例。
@Mapper
public interface CarMapper {
void updateCarFromDto(CarDto carDto, @MappingTarget Car car);
}
public class Customer {
private Long id;
private String name;
//getters and setter omitted for brevity
}
public class CustomerDto {
public Long id;
public String customerName;
}
@Mapper
public interface CustomerMapper {
CustomerMapper INSTANCE = Mappers.getMapper( CustomerMapper.class );
@Mapping(target = "name", source = "customerName")
Customer toCustomer(CustomerDto customerDto);
@InheritInverseConfiguration
CustomerDto fromCustomer(Customer customer);
}
MapStruct 支持使用构造函数来映射目标类型。执行映射时,MapStruct 会检查所映射的类型是否有构建器。如果没有构建器,则 MapStruct 会查找单个可访问的构造函数。当有多个构造函数时,执行以下操作来选择应该使用的构造函数:
指定Map的key映射到对应Bean的属性。
public class Customer {
private Long id;
private String name;
//getters and setter omitted for brevity
}
@Mapper
public interface CustomerMapper {
// 此时map对象中包括键customerName
@Mapping(target = "name", source = "customerName")
Customer toCustomer(Map map);
}
CarMapper mapper = Mappers.getMapper( CarMapper.class );
8种基本类型与其包装类,可以自动转化。
8种基本类型与String,可以自动转化。
@Mapper
public interface CarMapper {
@Mapping(source = "price", numberFormat = "$#.00")
CarDto carToCarDto(Car car);
@IterableMapping(numberFormat = "$#.00")
List prices(List prices);
}
@Mapper
public interface CarMapper {
@Mapping(source = "manufacturingDate", dateFormat = "dd.MM.yyyy")
CarDto carToCarDto(Car car);
@IterableMapping(dateFormat = "dd.MM.yyyy")
List stringListToDateList(List dates);
}
明确指定属性即可完成复制。
通过明确指定的属性值,完成复制。
定义公用映射器
public class DateMapper {
public String asString(Date date) {
return date != null ? new SimpleDateFormat( "yyyy-MM-dd" ).format( date ) : null;
}
public Date asDate(String date) {
try {
return date != null ? new SimpleDateFormat( "yyyy-MM-dd" ).parse( date ) : null;
} catch ( ParseException e ) {
throw new RuntimeException( e );
}
}
}
使用
@Mapper(uses=DateMapper.class)
public interface CarMapper {
CarDto carToCarDto(Car car);
}
使用限定符指定生成默认值方法
@Mapper
public interface MovieMapper {
@Mapping( target = "category", qualifiedByName = "CategoryToString", defaultValue = "DEFAULT" )
GermanRelease toGerman( OriginalRelease movies );
@Named("CategoryToString")
default String defaultValueForQualifier(Category cat) {
// some mapping logic
}
}
此时 category 为空时,将使用 defaultValueForQualifier 方法生成默认值。