zoukankan      html  css  js  c++  java
  • MapStruct 代替BeanUtil

    这篇博文不错:https://www.cnblogs.com/tanoak/articles/10302299.html

    1.pom.xml配置

     <dependency>
                <groupId>org.mapstruct</groupId>
                <artifactId>mapstruct-jdk8</artifactId>
                <version>1.2.0.Final</version>
            </dependency>  
    
    <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.5.1</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                        <annotationProcessorPaths>
                            <path>
                                <groupId>org.mapstruct</groupId>
                                <artifactId>mapstruct-processor</artifactId>
                                <version>1.2.0.Final</version>
                            </path>
                            <path>
                                <groupId>org.projectlombok</groupId>
                                <artifactId>lombok</artifactId>
                                <version>1.18.10</version>
                            </path>
                        </annotationProcessorPaths>
                    </configuration>
                </plugin>

    2.java实体代码

     1 @Data
     2 public class CarDto {
     3 
     4     private String make;
     5     private int seatCount;
     6     private String type;
     7 }
     8 
     9 
    10 @Data
    11 @AllArgsConstructor
    12 public class Car {
    13     private String make;
    14     private int numberOfSeats;
    15 }

    3.定义一个mapper接口,里面做实体装换

    1 @Mapper
    2 public interface CarMapper {
    3 
    4     CarMapper INSTANCE = Mappers.getMapper(CarMapper.class);
    5 
    6     @Mapping(source = "numberOfSeats", target = "seatCount")
    7     CarDto carToCarDto(Car car);
    8 
    9 }

    4.最后测试代码

     1 public class Test {
     2 
     3     public static void main(String[] args) {
     4         Car car = new Car( "Morris", 120 );
     5         //转换对象
     6         CarDto carDto = CarMapper.INSTANCE.carToCarDto( car );
     7 
     8         //测试
     9         System.out.println( carDto );
    10         System.out.println( carDto.getMake() );
    11         System.out.println( carDto.getSeatCount() );
    12         System.out.println(carDto.getType());
    13     }
    14 }

    还有其他高级用法....

  • 相关阅读:
    分页,上传,下载
    java web 开发模式
    EL/JSTL-jsp页面更简单的输出方式
    过滤器和监听器
    Servlet
    jsp标准动作
    java Bean
    寻找你的热情(1)——检查自己所处的位置
    fedora25 安装sublime text3
    python实例3-天气小模块
  • 原文地址:https://www.cnblogs.com/huzi007/p/12843829.html
Copyright © 2011-2022 走看看