mapstruct学习笔记

  1. 引入依赖
     <dependencies>
      <dependency>
            <groupId>org.mapstructgroupId>
            <artifactId>mapstructartifactId>
            <version>1.4.2.Finalversion>
        dependency>
    
        <dependency>
            <groupId>org.mapstructgroupId>
            <artifactId>mapstruct-processorartifactId>
            <version>1.4.2.Finalversion>
        dependency>
    
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.18.20version>
        dependency>
    
         
        <dependency>
            <groupId>javax.annotationgroupId>
            <artifactId>javax.annotation-apiartifactId>
            <version>1.3.2version>
        dependency>
     dependencies>
    
  2. 添加plugin
    <plugin>
        <groupId>org.apache.maven.pluginsgroupId>
        <artifactId>maven-compiler-pluginartifactId>
        <version>3.8.1version>
        <configuration>
            <source>1.8source>
            <target>1.8target>
            <annotationProcessorPaths>
                <path>
                    <groupId>org.projectlombokgroupId>
                    <artifactId>lombokartifactId>
                    <version>1.18.20version>
                path>
                <path>
                    <groupId>org.mapstructgroupId>
                    <artifactId>mapstruct-processorartifactId>
                    <version>1.4.2.Finalversion>
                path>
            annotationProcessorPaths>
        configuration>
    plugin>
    
  3. 编写do与bo实体
    // do 实体
    @Data // 新增
    @Accessors(chain = true)
    public class UserDO {
        // 用户编号
        private Integer id;
        // 用户名
        private String username;
        // 密码
        private String password;
    }
    // bo 实体
    @Data // 新增
    @Accessors(chain = true)
    public class UserBO {
       // 用户编号
       private Integer id;
       // 用户名
       private String username;
       // 密码
       private String password;
    }
    
  4. 编写convertor转换类
    @Mapper // <1>
    public interface UserConvert {
        UserConvert INSTANCE = Mappers.getMapper(UserConvert.class); // <2>
    
        UserBO convert(UserDO userDO);
    }
    
  5. 单元测试
    @Slf4j
    public class UserBOTest {
        @Test
        public void hello() {
            // 创建 UserDO 对象
            UserDO userDO = new UserDO()
                    .setId(1)
                    .setUsername("yudaoyuanma")
                    .setPassword("buzhidao");
            //  进行转换
            UserBO userBO = UserConvert.INSTANCE.convert(userDO);
            System.out.println(userBO.getId());
            System.out.println(userBO.getUsername());
            System.out.println(userBO.getPassword());
        }
    }
    
  6. 文档:https://mapstruct.org/documentation/stable/reference/html

你可能感兴趣的:(git,spring,java)