bean复制映射工具包mapstruct

简介

工作中经常会用到对象复制,属性覆盖等操作,除了常见的BeanUtil外,还有一个好用的编程式工具类mapstruct。

依赖

<dependency>
     <groupId>org.mapstruct</groupId>
     <artifactId>mapstruct-jdk8</artifactId>
     <version>1.1.0.Final</version>
</dependency>

使用demo

get和set用lombok自动生成了

@Data
public class Student {
    private Integer id;
    private String name;
    private Integer age;
    private String sex;
}

@Data
public class User {
    private Integer id;
    private String name;
    private Integer age;
    private String sex; 
}


import org.mapstruct.Mapper;
import org.mapstruct.Mappings;

@Mapper
public interface UserMapping {

	UserMapping instance = Mappers.get(UserMapping.class)


    /**
     * Student 转化为 User
     * @param Student
     * @return
     */
     User studentToUser(Student student);
}

在maven编译之后就可以看到在编译包中自动实现了对象复制

属性覆盖

也是差不多的操作,@MappingTarget指定被覆盖属性的目标对象

void studentToUser(@MappingTarget User user, Student student);

属性覆盖/转换

属性转换,这里以liststring互转为例

在这里插入图片描述

在build编译之后看到自动引用了类型转换的方法

在这里插入图片描述

也可以使用@Named注解指定转换的方法

@Mapper
public interface StudentMapper {
    StudentMapper INSTANCE = Mappers.getMapper(StudentMapper.class);

    @Mappings({
            @Mapping(source = "name1", target = "name2",defaultValue = "某某人"),
            @Mapping(target = "age2", expression = "java(java.lang.Integer.valueOf(student1.getAge1()))"),
            @Mapping(source = "createTime1", target = "createTime2", dateFormat = "yyyy-MM-dd HH:mm:ss:SSS"),
            @Mapping(source = "weight1", target = "weight2", numberFormat = "0.00"),
            @Mapping(target = "bloodType2", constant = "A 型血"),
            @Mapping(source = "sex1",target = "sex2",qualifiedByName = {"getBySexEnum"})
    })
    Student2 toStudent2(Student1 student1);

    @InheritConfiguration(name = "toStudent2")
    void updateStudent2(Student1 student1, @MappingTarget Student2 student2);

    @Named("getBySexEnum")
    default Integer getBySexEnum(SexEnum sexEnum){
        return sexEnum.getCode();
    }
}

指定null值时的策略

方法层级

@org.mapstruct.BeanMapping.BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
void xxxxx(@MappingTarget xxxxx target, xxxxx updateData);

class下全局

@Mapper(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
public interface xxxxx{
xxxx
}

List转换指定单个元素转换方法

@IterableMapping(qualifiedByName = "cvtAddEntity")
List<xxx> cvtAddEntityList(List<xxx> discountDetailList);


@Named("cvtAddEntity")
@Mappings({
        @Mapping(target = "id", ignore = true)
})
xxx cvtAddEntity(xxx discountDetail);

参考了文章
https://www.cnblogs.com/DDgougou/p/13365277.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值