來源:toutiao.com/i6891531055631696395
老鐵們是不是經常為寫一些實體轉換的原始代碼感到頭疼,尤其是實體字段特別多的時候。介紹一個開源項目 mapstruct ,可以輕松優雅的進行轉換,簡化你的代碼。
當然有的人喜歡寫get set,或者用BeanUtils 進行復制,代碼只是工具,本文只是提供一種思路。
先貼下官網地址吧:https://mapstruct.org/
廢話不多說,上代碼:
pom 配置:
UTF-8project.build.sourceEncoding>
1.8maven.compiler.source>
1.8maven.compiler.target>
1.4.1.Finalorg.mapstruct.version>
1.18.12org.projectlombok.version>
properties>
org.mapstructgroupId>
mapstructartifactId>
${org.mapstruct.version}version>
dependency>
org.projectlombokgroupId>
lombokartifactId>
${org.projectlombok.version}version>
providedscope>
dependency>
org.mapstructgroupId>
mapstruct-processorartifactId>
${org.mapstruct.version}version>
providedscope>
dependency>
dependencies>
關于lombok和mapstruct的版本兼容問題多說幾句,maven插件要使用3.6.0版本以上、lombok使用1.16.16版本以上,另外編譯的lombok mapstruct的插件不要忘了加上。否則會出現下面的錯誤:
No property named "aaa" exists in source parameter(s). Did you mean "null"?
這種異常就是lombok編譯異常導致缺少get setter方法造成的。還有就是缺少構造函數也會拋異常。
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private String name;
private int age;
private GenderEnum gender;
private Double height;
private Date birthday;
}
public enum GenderEnum {
Male("1", "男"),
Female("0", "女");
private String code;
private String name;
public String getCode() {
return this.code;
}
public String getName() {
return this.name;
}
GenderEnum(String code, String name) {
this.code = code;
this.name = name;
}
}
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class StudentVO {
private String name;
private int age;
private String gender;
private Double height;
private String birthday;
}
@Mapper
public interface StudentMapper {
StudentMapper INSTANCE = Mappers.getMapper(StudentMapper.class);
@Mapping(source = "gender.name", target = "gender")
@Mapping(source = "birthday", target = "birthday", dateFormat = "yyyy-MM-dd HH:mm:ss")
StudentVO student2StudentVO(Student student);
}
實體類是開發過程少不了的,就算是用工具生成肯定也是要有的,需要手寫的部分就是這個Mapper的接口,編譯完成后會自動生成相應的實現類
然后就可以直接用mapper進行實體的轉換了
public class Test {
public static void main(String[] args) {
Student student = Student.builder().name("小明").age(6).gender(GenderEnum.Male).height(121.1).birthday(new Date()).build();
System.out.println(student);
//這行代碼便是實際要用的代碼
StudentVO studentVO = StudentMapper.INSTANCE.student2StudentVO(student);
System.out.println(studentVO);
}
}
mapper可以進行字段映射,改變字段類型,指定格式化的方式,包括一些日期的默認處理。
可以手動指定格式化的方法:
@Mapper
public interface StudentMapper {
StudentMapper INSTANCE = Mappers.getMapper(StudentMapper.class);
@Mapping(source = "gender", target = "gender")
@Mapping(source = "birthday", target = "birthday", dateFormat = "yyyy-MM-dd HH:mm:ss")
StudentVO student2StudentVO(Student student);
default String getGenderName(GenderEnum gender) {
return gender.getName();
}
}
上面只是最簡單的實體映射處理,下面介紹一些高級用法
1.List 轉換
屬性映射基于上面的mapping配置
@Mapper
public interface StudentMapper {
StudentMapper INSTANCE = Mappers.getMapper(StudentMapper.class);
@Mapping(source = "gender.name", target = "gender")
@Mapping(source = "birthday", target = "birthday", dateFormat = "yyyy-MM-dd HH:mm:ss")
StudentVO student2StudentVO(Student student);
List students2StudentVOs(List studentList);
}
public static void main(String[] args) {
Student student = Student.builder().name("小明").age(6).gender(GenderEnum.Male).height(121.1).birthday(new Date()).build();
List list = new ArrayList<>();
list.add(student);
List result = StudentMapper.INSTANCE.students2StudentVOs(list);
System.out.println(result);
} 2.多對象轉換到一個對象
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private String name;
private int age;
private GenderEnum gender;
private Double height;
private Date birthday;
}
@Data
@AllArgsConstructor
@Builder
@NoArgsConstructor
public class Course {
private String courseName;
private int sortNo;
private long id;
}
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class StudentVO {
private String name;
private int age;
private String gender;
private Double height;
private String birthday;
private String course;
}
@Mapper
public interface StudentMapper {
StudentMapper INSTANCE = Mappers.getMapper(StudentMapper.class);
@Mapping(source = "student.gender.name", target = "gender")
@Mapping(source = "student.birthday", target = "birthday", dateFormat = "yyyy-MM-dd HH:mm:ss")
@Mapping(source = "course.courseName", target = "course")
StudentVO studentAndCourse2StudentVO(Student student, Course course);
}
public class Test {
public static void main(String[] args) {
Student student = Student.builder().name("小明").age(6).gender(GenderEnum.Male).height(121.1).birthday(new Date()).build();
Course course = Course.builder().id(1L).courseName("語文").build();
StudentVO studentVO = StudentMapper.INSTANCE.studentAndCourse2StudentVO(student, course);
System.out.println(studentVO);
}
}
3.默認值
@Mapper
public interface StudentMapper {
StudentMapper INSTANCE = Mappers.getMapper(StudentMapper.class);
@Mapping(source = "student.gender.name", target = "gender")
@Mapping(source = "student.birthday", target = "birthday", dateFormat = "yyyy-MM-dd HH:mm:ss")
@Mapping(source = "course.courseName", target = "course")
@Mapping(target = "name", source = "student.name", defaultValue = "張三")
StudentVO studentAndCourse2StudentVO(Student student, Course course);
}
END
2021年Java原創面試題庫連載中
更多內容,點擊上方名片查看
org.apache.maven.pluginsgroupId>
maven-compiler-pluginartifactId>
3.8.1version>
1.8source>
1.8target>
org.projectlombokgroupId>
lombokartifactId>
${org.projectlombok.version}version>
path>
org.mapstructgroupId>
mapstruct-processorartifactId>
${org.mapstruct.version}version>
path>
annotationProcessorPaths>
configuration>
plugin>
plugins>
build>
特別聲明:以上內容(如有圖片或視頻亦包括在內)為自媒體平臺“網易號”用戶上傳并發布,本平臺僅提供信息存儲服務。
Notice: The content above (including the pictures and videos if any) is uploaded and posted by a user of NetEase Hao, which is a social media platform and only provides information storage services.