zoukankan      html  css  js  c++  java
  • MapStruct

    GitHub

    https://github.com/mapstruct/mapstruct

    简介

    使用MapStruct

    Maven

    For Maven-based projects, add the following to your POM file in order to use MapStruct (the dependencies are available at Maven Central):

    对于基于Maven的项目,请将以下内容添加到POM文件中,以便使用MapStruct(依赖项在Maven Central上提供):

    ...
    <properties>
        <org.mapstruct.version>1.3.1.Final</org.mapstruct.version>
    </properties>
    ...
    <dependency>
        <groupId>org.mapstruct</groupId>
        <artifactId>mapstruct</artifactId>
        <version>${org.mapstruct.version}</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.mapstruct</groupId>
        <artifactId>mapstruct-processor</artifactId>
        <version>${org.mapstruct.version}</version>
        <scope>compile</scope>
    </dependency>
    ...
    

    IDE 插件

    建议安装MapStruct插件

    IDE 插件名称
    IntelliJ IDEA MapStruct Support

    示例

    准备以下两组实体类

    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class Car {
        private String make;
        private int numberOfSeats;
        private CarType type;
    }
    
    import lombok.Data;
    
    @Data
    public class CarDto {
        private String make;
        private int seatCount;
        private String type;
    }
    
    public enum CarType {
        SEDAN;
    }
    

    映射接口

    import org.mapstruct.Mapper;
    import org.mapstruct.Mapping;
    import org.mapstruct.factory.Mappers;
    
    @Mapper
    public interface CarMapper {
    
        CarMapper INSTANCE = Mappers.getMapper(CarMapper.class);
    
        @Mapping(source = "numberOfSeats", target = "seatCount")
        CarDto carToCarDto(Car car);
    }
    

    单元测试类

    import org.junit.jupiter.api.Test;
    
    import static org.assertj.core.api.Assertions.assertThat;
    
    public class CarMapperTests {
        @Test
        public void shouldMapCarToDto() {
            //given
            Car car = new Car( "Morris", 5, CarType.SEDAN );
    
            //when
            CarDto carDto = CarMapper.INSTANCE.carToCarDto( car );
    
            //then
            assertThat( carDto ).isNotNull();
            assertThat( carDto.getMake() ).isEqualTo( "Morris" );
            assertThat( carDto.getSeatCount() ).isEqualTo( 5 );
            assertThat( carDto.getType() ).isEqualTo( "SEDAN" );
        }
    }
    
  • 相关阅读:
    POJ 1386 判断欧拉回路
    POJ 1416 DFS
    POJ 1654 乱搞题?
    POJ 1703 带权并查集
    POJ 1442 Treap模板
    TYVJ 1941 BZOJ3038 上帝造题的七分钟2 并查集+树状数组
    POJ 2492 A Bug's Life 带权并查集
    AHOI 2009 (BZOJ1798)维护序列 seq (线段树好题?)
    Binary Tree Traversal
    Weekly Contest 111-------->944. Delete Columns to Make Sorted
  • 原文地址:https://www.cnblogs.com/fengzhentian/p/13508918.html
Copyright © 2011-2022 走看看