工作中经常会用到对象复制,属性覆盖等操作,除了常见的BeanUtil外,还有一个好用的编程式工具类mapstruct。
<dependency>
<groupId>org.mapstructgroupId>
<artifactId>mapstruct-jdk8artifactId>
<version>1.1.0.Finalversion>
dependency>
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();
}
}
方法层级
@org.mapstruct.BeanMapping.BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
void xxxxx(@MappingTarget xxxxx target, xxxxx updateData);
class下全局
@Mapper(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
public interface xxxxx{
xxxx
}
@IterableMapping(qualifiedByName = "cvtAddEntity")
List<xxx> cvtAddEntityList(List<xxx> discountDetailList);
@Named("cvtAddEntity")
@Mappings({
@Mapping(target = "id", ignore = true)
})
xxx cvtAddEntity(xxx discountDetail);