bean复制映射工具包mapstruct
Posted 好大的月亮
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);
属性覆盖/转换
属性转换,这里以list
和string
互转为例
在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();
参考了文章
https://www.cnblogs.com/DDgougou/p/13365277.html
以上是关于bean复制映射工具包mapstruct的主要内容,如果未能解决你的问题,请参考以下文章