0
  • 聊天消息
  • 系統(tǒng)消息
  • 評論與回復
登錄后你可以
  • 下載海量資料
  • 學習在線課程
  • 觀看技術(shù)視頻
  • 寫文章/發(fā)帖/加入社區(qū)
會員中心
創(chuàng)作中心

完善資料讓更多小伙伴認識你,還能領(lǐng)取20積分哦,立即完善>

3天內(nèi)不再提示

別再用BeanUtils了,這款PO VO DTO轉(zhuǎn)換神器不香么?

jf_ro2CN3Fa ? 來源:toutiao.com ? 2023-07-10 10:46 ? 次閱讀


老鐵們是不是經(jīng)常為寫一些實體轉(zhuǎn)換的原始代碼感到頭疼,尤其是實體字段特別多的時候。介紹一個開源項目 mapstruct ,可以輕松優(yōu)雅的進行轉(zhuǎn)換,簡化你的代碼。當然有的人喜歡寫get set,或者用BeanUtils 進行復制,代碼只是工具,本文只是提供一種思路。

先貼下官網(wǎng)地址吧:https://mapstruct.org/

廢話不多說,上代碼:

pom 配置:

<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<maven.compiler.source>1.8maven.compiler.source>
<maven.compiler.target>1.8maven.compiler.target>
<org.mapstruct.version>1.4.1.Finalorg.mapstruct.version>
<org.projectlombok.version>1.18.12org.projectlombok.version>
properties>

<dependencies>
<dependency>
<groupId>org.mapstructgroupId>
<artifactId>mapstructartifactId>
<version>${org.mapstruct.version}version>
dependency>


<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>${org.projectlombok.version}version>
<scope>providedscope>
dependency>


<dependency>
<groupId>org.mapstructgroupId>
<artifactId>mapstruct-processorartifactId>
<version>${org.mapstruct.version}version>
<scope>providedscope>
dependency>

dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-compiler-pluginartifactId>
<version>3.8.1version>
<configuration>
<source>1.8source>
<target>1.8target>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>${org.projectlombok.version}version>
path>
<path>
<groupId>org.mapstructgroupId>
<artifactId>mapstruct-processorartifactId>
<version>${org.mapstruct.version}version>
path>
annotationProcessorPaths>
configuration>
plugin>
plugins>
build>

關(guān)于lombok和mapstruct的版本兼容問題多說幾句,maven插件要使用3.6.0版本以上、lombok使用1.16.16版本以上,另外編譯的lombok mapstruct的插件不要忘了加上。否則會出現(xiàn)下面的錯誤:No property named "aaa" exists in source parameter(s). Did you mean "null"?

基于 Spring Boot + MyBatis Plus + Vue & Element 實現(xiàn)的后臺管理系統(tǒng) + 用戶小程序,支持 RBAC 動態(tài)權(quán)限、多租戶、數(shù)據(jù)權(quán)限、工作流、三方登錄、支付、短信、商城等功能

  • 項目地址:https://github.com/YunaiV/ruoyi-vue-pro
  • 視頻教程:https://doc.iocoder.cn/video/

這種異常就是lombok編譯異常導致缺少get setter方法造成的。還有就是缺少構(gòu)造函數(shù)也會拋異常。

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
publicclassStudent{

privateStringname;
privateintage;
privateGenderEnumgender;
privateDoubleheight;
privateDatebirthday;

}
publicenumGenderEnum{
Male("1","男"),
Female("0","女");

privateStringcode;
privateStringname;

publicStringgetCode(){
returnthis.code;
}

publicStringgetName(){
returnthis.name;
}

GenderEnum(Stringcode,Stringname){
this.code=code;
this.name=name;
}
}
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
publicclassStudentVO{
privateStringname;
privateintage;
privateStringgender;
privateDoubleheight;
privateStringbirthday;
}
@Mapper
publicinterfaceStudentMapper{

StudentMapperINSTANCE=Mappers.getMapper(StudentMapper.class);

@Mapping(source="gender.name",target="gender")
@Mapping(source="birthday",target="birthday",dateFormat="yyyy-MM-ddHHss")
StudentVOstudent2StudentVO(Studentstudent);

}

實體類是開發(fā)過程少不了的,就算是用工具生成肯定也是要有的,需要手寫的部分就是這個Mapper的接口,編譯完成后會自動生成相應(yīng)的實現(xiàn)類

ee323a9e-1eca-11ee-962d-dac502259ad0.png

然后就可以直接用mapper進行實體的轉(zhuǎn)換了

publicclassTest{

publicstaticvoidmain(String[]args){

Studentstudent=Student.builder().name("小明").age(6).gender(GenderEnum.Male).height(121.1).birthday(newDate()).build();
System.out.println(student);
//這行代碼便是實際要用的代碼
StudentVOstudentVO=StudentMapper.INSTANCE.student2StudentVO(student);
System.out.println(studentVO);

}

}
ee323a9e-1eca-11ee-962d-dac502259ad0.png

mapper可以進行字段映射,改變字段類型,指定格式化的方式,包括一些日期的默認處理。

可以手動指定格式化的方法:

@Mapper
publicinterfaceStudentMapper{

StudentMapperINSTANCE=Mappers.getMapper(StudentMapper.class);

@Mapping(source="gender",target="gender")
@Mapping(source="birthday",target="birthday",dateFormat="yyyy-MM-ddHHss")
StudentVOstudent2StudentVO(Studentstudent);

defaultStringgetGenderName(GenderEnumgender){
returngender.getName();
}

}

上面只是最簡單的實體映射處理,下面介紹一些高級用法

1、List 轉(zhuǎn)換

屬性映射基于上面的mapping配置

@Mapper
publicinterfaceStudentMapper{

StudentMapperINSTANCE=Mappers.getMapper(StudentMapper.class);

@Mapping(source="gender.name",target="gender")
@Mapping(source="birthday",target="birthday",dateFormat="yyyy-MM-ddHHss")
StudentVOstudent2StudentVO(Studentstudent);


Liststudents2StudentVOs(ListstudentList);

}
publicstaticvoidmain(String[]args){

Studentstudent=Student.builder().name("小明").age(6).gender(GenderEnum.Male).height(121.1).birthday(newDate()).build();

Listlist=newArrayList<>();
list.add(student);
Listresult=StudentMapper.INSTANCE.students2StudentVOs(list);
System.out.println(result);
}
ee664ae6-1eca-11ee-962d-dac502259ad0.png

基于 Spring Cloud Alibaba + Gateway + Nacos + RocketMQ + Vue & Element 實現(xiàn)的后臺管理系統(tǒng) + 用戶小程序,支持 RBAC 動態(tài)權(quán)限、多租戶、數(shù)據(jù)權(quán)限、工作流、三方登錄、支付、短信、商城等功能

  • 項目地址:https://github.com/YunaiV/yudao-cloud
  • 視頻教程:https://doc.iocoder.cn/video/

2、多對象轉(zhuǎn)換到一個對象

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
publicclassStudent{

privateStringname;
privateintage;
privateGenderEnumgender;
privateDoubleheight;
privateDatebirthday;

}
@Data
@AllArgsConstructor
@Builder
@NoArgsConstructor
publicclassCourse{

privateStringcourseName;
privateintsortNo;
privatelongid;

}
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
publicclassStudentVO{
privateStringname;
privateintage;
privateStringgender;
privateDoubleheight;
privateStringbirthday;
privateStringcourse;
}
@Mapper
publicinterfaceStudentMapper{

StudentMapperINSTANCE=Mappers.getMapper(StudentMapper.class);

@Mapping(source="student.gender.name",target="gender")
@Mapping(source="student.birthday",target="birthday",dateFormat="yyyy-MM-ddHHss")
@Mapping(source="course.courseName",target="course")
StudentVOstudentAndCourse2StudentVO(Studentstudent,Coursecourse);

}
publicclassTest{

publicstaticvoidmain(String[]args){

Studentstudent=Student.builder().name("小明").age(6).gender(GenderEnum.Male).height(121.1).birthday(newDate()).build();
Coursecourse=Course.builder().id(1L).courseName("語文").build();

StudentVOstudentVO=StudentMapper.INSTANCE.studentAndCourse2StudentVO(student,course);
System.out.println(studentVO);
}

}
ee8890c4-1eca-11ee-962d-dac502259ad0.png

基于 Spring Cloud Alibaba + Gateway + Nacos + RocketMQ + Vue & Element 實現(xiàn)的后臺管理系統(tǒng) + 用戶小程序,支持 RBAC 動態(tài)權(quán)限、多租戶、數(shù)據(jù)權(quán)限、工作流、三方登錄、支付、短信、商城等功能

  • 項目地址:https://gitee.com/zhijiantianya/yudao-cloud
  • 視頻教程:https://doc.iocoder.cn/video/

3、默認值

@Mapper
publicinterfaceStudentMapper{

StudentMapperINSTANCE=Mappers.getMapper(StudentMapper.class);

@Mapping(source="student.gender.name",target="gender")
@Mapping(source="student.birthday",target="birthday",dateFormat="yyyy-MM-ddHHss")
@Mapping(source="course.courseName",target="course")
@Mapping(target="name",source="student.name",defaultValue="張三")
StudentVOstudentAndCourse2StudentVO(Studentstudent,Coursecourse);

}
eea4f232-1eca-11ee-962d-dac502259ad0.png


聲明:本文內(nèi)容及配圖由入駐作者撰寫或者入駐合作網(wǎng)站授權(quán)轉(zhuǎn)載。文章觀點僅代表作者本人,不代表電子發(fā)燒友網(wǎng)立場。文章及其配圖僅供工程師學習之用,如有內(nèi)容侵權(quán)或者其他違規(guī)問題,請聯(lián)系本站處理。 舉報投訴
  • spring
    +關(guān)注

    關(guān)注

    0

    文章

    335

    瀏覽量

    14259
  • 開源項目
    +關(guān)注

    關(guān)注

    0

    文章

    36

    瀏覽量

    7144

原文標題:別再用 BeanUtils 了,這款 PO VO DTO 轉(zhuǎn)換神器不香么?

文章出處:【微信號:芋道源碼,微信公眾號:芋道源碼】歡迎添加關(guān)注!文章轉(zhuǎn)載請注明出處。

收藏 人收藏

    評論

    相關(guān)推薦

    THS4509運放給+5V單電源供電,請問輸出電壓Vo+ - Vo-最大能輸出多少V?

    你好,請問這款運放給+5V單電源供電,請問輸出電壓Vo+ - Vo-最大能輸出多少V?
    發(fā)表于 08-01 08:16

    奈兒呼啦圈包包,絕不覺得有點蛋疼的設(shè)計

    `巴黎時裝周上,奈兒推出了一款呼啦圈包包,這款超大的信封式單肩包以奈兒經(jīng)典的菱形格真皮制成,用兩個呼啦圈來做包的支架兼背帶。設(shè)計師說:這是一款為海邊度假打造的產(chǎn)品。你要一個能塞下浴巾的包吧?你可以把它隨手放在沙灘上,還能在包
    發(fā)表于 10-12 14:35

    聲音有PO-PO雜聲?

    `大家討論下這個問題: 一個繼電器去切換A B兩路功放的聲音, 一個喇叭發(fā)聲, 在切換的過程中有PO-PO聲音 ,每次切換到A或者切換到B 都有PO的一聲 ! 大伙幫忙分析下,多謝!`
    發(fā)表于 11-16 15:36

    厲害了word哥,這款手機無線充電產(chǎn)品牛掰,你們怎么看???

    今天無意間在淘寶發(fā)現(xiàn)這款手機無線充電神器?! ≡诰W(wǎng)上搜下,它叫MAGQI,在家里,車上,戶外都可以給手機無線充電。  這里分享給下,大家看看有什么想法?  家里使用:  車上使用 
    發(fā)表于 01-03 15:10

    請問有人熟悉MSK4351這款IPM智能功率芯片?這款芯片的外圍電路怎么搭建?有做過的

    本帖最后由 一只耳朵怪 于 2018-6-6 08:54 編輯 用MSK4351做無刷直流電機的驅(qū)動芯片,但是datasheet看的云里霧里的!這款芯片的外圍電路怎么搭建?有做過的?
    發(fā)表于 06-05 20:34

    千萬別再用這臺示波器,我怕你會愛上它!

    千萬別再用這臺示波器,我怕你會愛上它!
    發(fā)表于 05-30 21:01

    iOS版餓使用的開源項目

    前不久,猿妹才發(fā)現(xiàn)支付寶使用了三十多款開源軟件,今天打開餓發(fā)現(xiàn),餓也使用了33款開源軟件。
    的頭像 發(fā)表于 05-31 14:24 ?8531次閱讀

    體驗未來餓無人機配送外賣服務(wù)

    在2017年世界無人系統(tǒng)大會上,餓首次公開亮相其外賣無人機,展示的是餓內(nèi)部研發(fā)的第3代產(chǎn)品“E7”(中文名:翼),餓
    發(fā)表于 07-18 00:42 ?2064次閱讀

    蘋果iPhone 13系列真的那么嗎?

    九月將至,廣大果粉們期盼已久的 iPhone 13 近在眼前。擁有我國知名食品調(diào)料品牌“傾情代言”的 iPhone 13 系列,真的那么嗎? 這就體現(xiàn)出不同文化之間的差異。最近一項針對國外
    的頭像 發(fā)表于 06-28 10:41 ?2659次閱讀

    PO VO DTO轉(zhuǎn)換神器的思路

    當然有的人喜歡寫get set,或者用BeanUtils 進行復制,代碼只是工具,本文只是提供一種思路。 pom 配置: properties
    的頭像 發(fā)表于 10-12 11:13 ?1383次閱讀

    MapStruct是用來做什么的

    首先來了解一下DTO,DTO簡單的理解就是做數(shù)據(jù)傳輸對象的,類似于VO,但是VO用于傳輸?shù)角岸恕?/div>
    的頭像 發(fā)表于 06-15 17:02 ?1458次閱讀

    如何分清PO、VO、DAO、BO、DTO、POJO?

    基于 Spring Boot + MyBatis Plus + Vue & Element 實現(xiàn)的后臺管理系統(tǒng) + 用戶小程序,支持 RBAC 動態(tài)權(quán)限、多租戶、數(shù)據(jù)權(quán)限、工作流、三方登錄、支付、短信、商城等功能
    發(fā)表于 03-07 09:38 ?1133次閱讀

    POVO、DAO、BO、DTO、POJO應(yīng)該怎么分層

    一個項目中不一定都能用得上全部的分層規(guī)約,但十分有必要了解每一種的用法,便于去閱讀其他人的代碼。同樣的,雖然遵守規(guī)約寫代碼可能會略微拉低你寫代碼的速度(PS:多寫一些實體類),但越是規(guī)范化,模板化的東西,后期的維護成本和學習成本會越低。
    的頭像 發(fā)表于 05-18 11:00 ?911次閱讀

    深入淺出聊PLC技術(shù),無線智能家居瞬間「」?

    近兩年,PLC技術(shù)在智能家居領(lǐng)域刷出了存在感。尤其是在華為的推動下,PLC成為了一種「觸手可得」的全屋智能解決方案,讓WiFi、ZigBee、藍牙等技術(shù)瞬間「」。本文,「智哪兒」從三個方面解讀
    的頭像 發(fā)表于 04-15 14:56 ?2332次閱讀
    深入淺出聊PLC技術(shù),無線智能家居瞬間「<b class='flag-5'>不</b><b class='flag-5'>香</b><b class='flag-5'>了</b>」?

    別再用offset和limit分頁,OFFSET和LIMIT有什么問題?

    不需要擔心數(shù)據(jù)庫性能優(yōu)化問題的日子已經(jīng)一去不復返
    的頭像 發(fā)表于 08-11 09:37 ?658次閱讀
    <b class='flag-5'>別再用</b>offset和limit分頁<b class='flag-5'>了</b>,OFFSET和LIMIT有什么問題?