mapstruct使用

mapstruct使用

官方文档地址

官方github地址

介绍

Mapstruct可以简化领域模型DO-DTO转换.通常转换发生在代码运行阶段或编译阶段,运行阶段的转换一般通过反射去做,但是这种方式比较消耗资源,会拖慢程序比如ModelMapper,另外一种在编译时进行处理,处理方式类似于lombok例如mapstruct.

gradle 使用

Using the plugins DSL

plugins {
    ...
    id 'net.ltgt.apt' version '0.15'
}

apply plugin: 'net.ltgt.apt-idea'
apply plugin: 'net.ltgt.apt-eclipse'

dependencies {
    ...
    compile 'org.mapstruct:mapstruct:1.3.0.Final'

    annotationProcessor 'org.mapstruct:mapstruct-processor:1.3.0.Final'
    testAnnotationProcessor 'org.mapstruct:mapstruct-processor:1.3.0.Final' // if you are using mapstruct in test code
}

Using legacy plugin application

buildscript {
  repositories {
    maven {
      url "https://plugins.gradle.org/m2/"
    }
  }
  dependencies {
    classpath "net.ltgt.gradle:gradle-apt-plugin:0.21"
  }
}

apply plugin: "net.ltgt.apt"

dependencies {
    ...
    compile 'org.mapstruct:mapstruct:1.3.0.Final'

    annotationProcessor 'org.mapstruct:mapstruct-processor:1.3.0.Final'
    testAnnotationProcessor 'org.mapstruct:mapstruct-processor:1.3.0.Final' // if you are using mapstruct in test code
}
...

maven 使用


    1.3.0.Final

...

    
        org.mapstruct
        mapstruct
        ${org.mapstruct.version}
    

...

    
        
            org.apache.maven.plugins
            maven-compiler-plugin
            3.5.1 
            
                1.8 
                1.8 
                
                    
                        org.mapstruct
                        mapstruct-processor
                        ${org.mapstruct.version}
                    
                    
                
            
        
    

检查IDE 设置

IntelliJ

Make sure that you have at least IntelliJ 2018.2.x (needed since support for annotationProcessors from the maven-compiler-plugin is from that version)

检查方式: Enable annotation processing in IntelliJ (Build, Execution, Deployment -> Compiler -> Annotation Processors)

代码编写

// 举例car实体
public class Car {

    private String make;
    private int numberOfSeats;
    private CarType type;

    //省略constructor, getters, setters etc. 建议使用lombok
}
// 举例cardto
public class CarDto {

    private String make;
    private int seatCount;
    private String type;

    //省略 constructor, getters, setters etc.建议使用lombok
}
// 举例mapper
@Mapper
public interface CarMapper {

    CarMapper INSTANCE = Mappers.getMapper( CarMapper.class );

    @Mapping(source = "numberOfSeats", target = "seatCount")
    CarDto carToCarDto(Car car);
}

进阶用法

  1. 创建mapper 抽象接口
public interface EntityMapper {

    /**
     * DTO转Entity
     * @param dto
     * @return
     */
    E toEntity(D dto);

    /**
     * Entity转DTO
     * @param entity
     * @return
     */
    D toDto(E entity);

    /**
     * DTO集合转Entity集合
     * @param dtoList
     * @return
     */
    List  toEntity(List dtoList);

    /**
     * Entity集合转DTO集合
     * @param entityList
     * @return
     */
    List  toDto(List entityList);
}
  1. 继承抽象接口
@Data
public class PushLogDTO implements Serializable {
    ... //省略 constructor, getters, setters etc.建议使用lombok
}

@Data
public class PushLog extends EntityBase {
    ... //省略 constructor, getters, setters etc.建议使用lombok

}

@Mapper(componentModel = "spring", uses = {PushResponseMapper.class}, unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface PushLogMapper extends EntityMapper {

}
  1. 通过Decorator对抽象类方法进行扩展
//定义Decorator
public abstract class Decorator implements EntityMapper {
    public EntityMapper entityMapper;

    public Decorator(EntityMapper entityMapper) {
        this.entityMapper = entityMapper;
    }

}

public class PushLogMapperDecorator extends Decorator {

    public PushLogMapperDecorator(PushLogMapper pushLogMapper) {
        super(pushLogMapper);
    }



    public PushLog toEntity(PushLogDTO dto) {
        System.out.println("=================PushLogMapperDecorator输出==============");
        return (PushLog) entityMapper.toEntity(dto);
    }

    
    public PushLogDTO toDto(PushLog entity) {
        System.out.println("=================PushLogMapperDecorator输出开始==============");
        System.out.println(entity.toString());
        System.out.println("=================PushLogMapperDecorator输出结束==============");
        return (PushLogDTO) entityMapper.toDto(entity);
    }

    public List toEntity(List dtoList) {
        System.out.println("=================PushLogMapperDecorator输出==============");
        return (List) entityMapper.toEntity(dtoList);
    }

    public List toDto(List entityList) {
        System.out.println("=================PushLogMapperDecorator输出==============");
        return (List) entityMapper.toDto(entityList);
    }
}
//使用
 Decorator decorator =new PushLogMapperDecorator(pushLogMapper);
 //mappper转换
 System.out.println(PageUtil.toPage(page.map(decorator::toDto)));
  1. 使用注解

@Mapper :
标记这个接口作为一个映射接口,并且是编译时 MapStruct 处理器的入口
@Mapper(componentModel = “spring”),如果是属性中包含其它类以及该类已经存在 Mapper 则注解中加上 users = {类名.class}。componentModel = “spring” 该配置表示生成的实现类默认加上 spring @Component 注解,使用时可直接通过 @Autowire 进行注入

@Mapping : 解决源对象和目标对象中,属性名字不同的情况.参数numberFormat = "$#.00"用于对于数值类型的参数进行格式化输出.参数dateFormat = "dd.MM.yyyy"对于日期格式参数进行格式化输出

编译

gradle

gradlew clean build

maven

mvn clean install

查看代码

idea设置Anotation annotationProcessor 生成路径下(默认为generated)
++build\generated\sources\annotationProcessor++

你可能感兴趣的:(后端开发)