MapStruct:JavaBean之间的数据映射
//代码一
@Mapper(componentModel = "spring", injectionStrategy = InjectionStrategy.CONSTRUCTOR, uses = xxxControllerConverter.class) public interface xxxControllerMapper {
@Mapping(target = "page", ignore = true) @Mapping(target = "name", source = "firstName") @Mapping(target = "code", source = "code", qualifiedByName = "trimSpace") xxServiceIn map(xxIn in); @BeanMapping(ignoreByDefault = true) @Mapping(target = "code", source = "code", qualifiedByName = "trimSpace") @Mapping(target = "type", source = "type") @Mapping(target = "name", source = "name") @Mapping(target = "list", source = "list") xxxxServiceIn map(xxxxIn in);
//多转一
@Mapping(source = "in.securitiesCode", target = "securitiesCode", qualifiedByName = "upperCase")
xxServiceEntryIn map(xxEntryIn in, CountryCode countryCode);
}
代码解释:
①componentModel = "spring",
spring: 生成的实现类上面会自动添加一个@Component注解,可以通过Spring的 @Autowired方式进行注入
②injectionStrategy = InjectionStrategy.CONSTRUCTOR,
②injectionStrategy = InjectionStrategy.CONSTRUCTOR,
③uses = xxxControllerConverter.class:通过uses配置类型转换(代码一结合代码二配套处理,③⑨结合看)
④@Mapping(target = "page", ignore = true):忽略page,不进行映射
⑤@Mapping(target = "name", source = "firstName"):firstName映射到name
⑥@Mapping(target = "code", source = "code", qualifiedByName = "trimSpace"):使用@Named注解进行标注,并在 @Mapping 注解中使用 qualifiedByName 表明使用哪个方法进行处理转换,⑥⑩结合看
⑦@BeanMapping(ignoreByDefault = true):忽略MapStruct的默认映射行为,通过@Mapping 指定所有映射,不指定不映射
⑧@Mapping(target = "list", source = "list"):对象集合可以直接映射
⑦@BeanMapping(ignoreByDefault = true):忽略MapStruct的默认映射行为,通过@Mapping 指定所有映射,不指定不映射
⑧@Mapping(target = "list", source = "list"):对象集合可以直接映射
//代码二
@Component @Named("xxxControllerConverter") public class xxxControllerConverter { @Named("trimSpace") public String trimSpace(final String str) { ... } }
⑨@Named("xxxControllerConverter")
⑩@Named("trimSpace")
list对象可以直接映射赋值(深克隆赋值)
List<Object> mapByList(List<Object> details);
更新bean对象:
我们不是想返回一个新的 Bean 对象, 而是希望更新传入对象的一些属性,注解 @MappingTarget后面跟的对象会被更新。
现象结果:在编译完成后,在target包class文件中相同位置中会生成对应的impl文件
这位大哥写的比较详细: https://www.cnblogs.com/gotten/p/13052911.html