美文网首页
模型之间相互转换

模型之间相互转换

作者: 尼尔君 | 来源:发表于2020-08-14 10:01 被阅读0次

    使用 MapStruct

    1.以maven形式添加

      <org.mapstruct.version>1.3.0.Final</org.mapstruct.version>
    
     <dependency>
                <groupId>org.mapstruct</groupId>
                <artifactId>mapstruct-jdk8</artifactId>
                <version>${org.mapstruct.version}</version>
            </dependency>
            <dependency>
                <groupId>org.mapstruct</groupId>
                <artifactId>mapstruct-processor</artifactId>
                <version>${org.mapstruct.version}</version>
            </dependency>
    

    2.举例: UserEntity 转换成UserVO(不包含password)

    创建映射Mapper

    @Mapper
    public interface ModelMapper {
        UserVO covertVo(UserEntity userEntity);
    }
    
    
       ModelMapper mapper = Mappers.getMapper(ModelMapper.class);
       UserVO userVO = mapper.covertVo(userEntity);
    

    不同字段映射

    @Data
    public class UserEntity {
        private Long id ;
        private String username;
        private String password;
        private String nickname;
    
    }
    @Data
    public class UserVO {
        private Long id ;
        private String username;
        private String nick;
    }
    
    

    映射文件编辑

    @Mapper
    public interface ModelMapper {
        
        @Mapping(source = "nickname" , target = "nick")
        UserVO covertVo(UserEntity userEntity);
    }
    
    

    多个

    @Mapper
    public interface ModelMapper {
    
        @Mapping(source = "Id" , target = "id")
        @Mapping(source = "nickname" , target = "nick")
        UserVO covertVo(UserEntity userEntity);
    }
    
    
    @Mapper
    public interface ModelMapper {
    
        @Mappings({
                @Mapping(source = "Id", target = "id"),
                @Mapping(source = "nickname", target = "nick")
        })
        UserVO covertVo(UserEntity userEntity);
    }
    
    

    相关文章

      网友评论

          本文标题:模型之间相互转换

          本文链接:https://www.haomeiwen.com/subject/vxtgdktx.html