可以写一个父类方法省去很多代码
import java.util.Collection;
import java.util.Objects;
import org.mapstruct.InheritConfiguration;
import org.mapstruct.MapperConfig;
/**
* 基础转换类,提供基本的几个方法,直接继承就可以; 字段不一致的,如果有需要写Mapping的写在对应方法上 并且接口类上一定要加上{@link org.mapstruct.Mapper}注解
* <p>
* Mapper 注解需自己定义实例:BaseMapStruct INSTANCE = Mappers.getMapper(BaseMapStruct.class);
* <p>
* Mapper(componentModel = "spring") 此注解可通过spring进行注入。
* <p>
* 官网:https://mapstruct.org
*
* @param <SOURCE>
* @param <TARGET>
* @author wangjy76
*/
@MapperConfig
public interface BaseConverter<SOURCE, TARGET> {
default String getLabel(Integer dictValue, String dictType) {
return Objects.requireNonNull(BeanFactory.getBean(SysDictDataMapper.class))
.selectDictLabel(dictType, dictValue);
}
/**
* 映射同名属性
*
* @param source
* @return
*/
@InheritConfiguration(name = "sourceToTarget")
TARGET sourceToTarget(SOURCE source);
/**
* 反向,映射同名属性
*
* @param target
* @return
*/
@InheritConfiguration(name = "targetToSource")
SOURCE targetToSource(TARGET target);
/**
* 映射同名属性,集合形式
*
* @param sources
* @return
*/
@InheritConfiguration(name = "sourceToTarget")
Collection<TARGET> sourceToTarget(Collection<SOURCE> sources);
/**
* 反向,映射同名属性,集合形式
*
* @param targets
* @return
*/
@InheritConfiguration(name = "targetToSource")
Collection<SOURCE> targetToSource(Collection<TARGET> targets);
}
再定义一个转换的接口
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;
@Mapper
public interface ClassConverter extends BaseConverter<PO, VO> {
ClassConverter INSTANCE = Mappers.getMapper(ClassConverter.class);
@Mappings({
@Mapping(target = "statusLabel", expression = "java(getLabel(po.getStatus(),\"status\"))"),
})
VO sourceToTarget(Po po);
}
方法中直接调用
(List<VO>) ClassConverter.INSTANCE.sourceToTarget(POList);