Java實(shí)體映射工具M(jìn)apStruct使用方法詳解
1.序
通常在后端開發(fā)中經(jīng)常不直接返回實(shí)體Entity類,經(jīng)過處理轉(zhuǎn)換返回前端,前端提交過來的對象也需要經(jīng)過轉(zhuǎn)換Entity實(shí)體才做存儲;通常使用的BeanUtils.copyProperties方法也比較粗暴,不僅效率低下(使用反射)而且僅映射相同名的屬性,多數(shù)情況下還需要手動編寫對應(yīng)的轉(zhuǎn)換方法實(shí)現(xiàn)。
插件MapStruct以接口方法結(jié)合注解優(yōu)雅實(shí)現(xiàn)對象轉(zhuǎn)換,MapStruct生成器生成代碼以更貼近原生的Setter、Getter方法處理屬性映射更為高效。
https://github.com/mapstruct/mapstruct/
https://github.com/mapstruct/mapstruct-examples
2.簡單用例
實(shí)體對象User
@Data @AllArgsConstructor public class User { private int id; private String name; private int age; private String address; }
轉(zhuǎn)換對象UserVO
@Mapper public interface UserConvert { UserConvert INSTANCE = Mappers.getMapper(UserConvert.class); @Mapping(source = "name", target = "userName") UserVO toVO(User entity); }
轉(zhuǎn)換接口
@Test public void contextLoads() { User user = new User(0, "Tester", 1, "上海市徐匯區(qū)"); UserVO userVO = UserConvert.INSTANCE.toVO(user); }
使用示例
@Test public void contextLoads() { User user = new User(0, "Tester", 1, "上海市徐匯區(qū)"); UserVO userVO = UserConvert.INSTANCE.toVO(user); }
3.使用詳解
1)關(guān)于接口注解@Mapper幾種屬性用法詳解
uses 使用其他手動編寫的或者其他Mapper接口覆寫相關(guān)的轉(zhuǎn)換方法,不能循環(huán)引用
@Mapper(uses=DateMapper.class)
imports 引用相關(guān)類,允許通過mapping.expression()、mapping.defaultExpression()直接使用這些類型
@Mapper(imports = DateUtil.class) public interface UserConvert { UserConvert INSTANCE = Mappers.getMapper(UserConvert.class); @Mappings({ @Mapping(source = "name", target = "userName"), // 以指定方法轉(zhuǎn)換屬性,這里如果不使用imports,則需要寫全引用類包路徑 @Mapping(target = "birthday", expression = "java(DateUtil.formatDate(entity.getBirthday()))") }) UserVO toVO(User entity); }
unmappedSourcePolicy、unmappedTargetPolicy 針對源類型/目標(biāo)類型中未映射屬性的反饋策略
typeConversionPolicy 針對有損轉(zhuǎn)換的反饋策略,例如Long轉(zhuǎn)Integer
反饋策略主要有三種:IGNORE,默認(rèn)值,忽略未映射的字段。WARN,警告。ERROR,報錯
@Mapper(unmappedSourcePolicy = ReportingPolicy.ERROR)
componentModel 指定生成映射器實(shí)例的模式,主要有四種:
default,不主動生成實(shí)例,通常以Mappers.getMapper(Class)實(shí)例化。
cdi,以CDI標(biāo)準(zhǔn)實(shí)例化映射器,使用@Inject注入相關(guān)實(shí)例,
spring,Spring Bean方式實(shí)例化,
jsr330,jsr330標(biāo)準(zhǔn)實(shí)例化
@Mapper(componentModel = "spring") public interface UserConvert { @Mapping(source = "name", target = "userName") UserVO toVO(User entity); }
@Autowired private UserConvert userConvert;
implementationName 指定實(shí)現(xiàn)類名稱,映射生成器接口會自動生成實(shí)現(xiàn)類<CLASS_NAME>Impl,使用此屬性可避免類沖突
implementationPackage 指定實(shí)現(xiàn)類包路徑
config 指定配置類,由指定的@MapperConfig配置類,config導(dǎo)入相關(guān)配置
配置類
@MapperConfig( uses = DateUtil.class, unmappedSourcePolicy = ReportingPolicy.WARN ) public interface UserConfig { }
導(dǎo)入配置類
@Mapper(componentModel = "spring", config = UserConfig.class)
collectionMappingStrategy 集合映射策略,這里注意集合映射時,如果集合中的類型已有對應(yīng)轉(zhuǎn)換方法,集合轉(zhuǎn)換時會優(yōu)先使用
@Mappings({ @Mapping(source = "name", target = "userName"), @Mapping(target = "birthday", expression = "java(DateUtil.formatDate(entity.getBirthday()))") }) UserVO toVO(User entity); List<UserVO> collectionCvt(List<User> entities);
GENERATED CODE 生成器生成代碼
public List<UserVO> collectionCvt(List<User> entities) { if (entities == null) { return null; } else { List<UserVO> list = new ArrayList(entities.size()); Iterator var3 = entities.iterator(); while(var3.hasNext()) { User user = (User)var3.next(); // 集合轉(zhuǎn)換時優(yōu)先使用了已定義的toVO方法 list.add(this.toVO(user)); } return list; } }
nullValueMappingStrategy null作為源值映射策略;RETURN_NULL默認(rèn)返回null, RETURN_DEFAULT返回默認(rèn)值,對于對象會通過構(gòu)造器自動構(gòu)造對象返回,集合會返回空集合
當(dāng)值為RETURN_DEFAULT時,如果映射規(guī)則中包含Mapping.expression、Mapping.constant必須手動判空處理,否則NPE
@MapperConfig(nullValueMappingStrategy = NullValueMappingStrategy.RETURN_DEFAULT)
NullValuePropertyMappingStrategy null作為源屬性映射策略;SET_TO_NULL默認(rèn)返回null,SET_TO_DEFAULT返回默認(rèn)值,IGNORE 忽略該值,以目標(biāo)對象已存在的值為準(zhǔn)
MappingInheritanceStrategy 繼承方法級映射配置策略:EXPLICIT 顯示使用InheritConfiguration生效。
AUTO_INHERIT_FROM_CONFIG 自動繼承正向轉(zhuǎn)換的配置。AUTO_INHERIT_REVERSE_FROM_CONFIG 自動繼承反向轉(zhuǎn)換的配置。AUTO_INHERIT_ALL_FROM_CONFIG 都繼承
@MapperConfig( mappingInheritanceStrategy = MappingInheritanceStrategy.EXPLICIT )
@InheritConfiguration void cvtVO(User entity, @MappingTarget UserVO vo);
nullValueCheckStrategy 空值監(jiān)測策略
2) 其他方法級別注解
@InheritInverseConfiguration 反向轉(zhuǎn)換時繼承映射規(guī)則
@Mapping 配置類型屬性的映射規(guī)則;
dateFormat 格式化日期
@Mapping(target = "birthday", dateFormat = "yyyy-MM-dd HH:mm:ss")
numberFormat 數(shù)字格式化
@Mapping(target = "price", numberFormat = "$#.00")
constant 常量
@Mapping(target = "age", constant = "0")
總結(jié)
到此這篇關(guān)于Java實(shí)體映射工具M(jìn)apStruct使用的文章就介紹到這了,更多相關(guān)Java實(shí)體映射工具M(jìn)apStruct內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring?boot?自定義?Starter及自動配置的方法
Starter?組件是?Spring?boot?的一個核心特性,Starter組件的出現(xiàn)極大的簡化了項(xiàng)目開發(fā),這篇文章主要介紹了Spring?boot?自定義?Starter?及?自動配置,需要的朋友可以參考下2022-12-12java全角、半角字符的關(guān)系以及轉(zhuǎn)換詳解
這篇文章主要介紹了2013-11-11Spark隨機(jī)森林實(shí)現(xiàn)票房預(yù)測
這篇文章主要為大家詳細(xì)介紹了Spark隨機(jī)森林實(shí)現(xiàn)票房預(yù)測,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-08-08java unicode轉(zhuǎn)碼為中文實(shí)例
這篇文章主要介紹了java unicode轉(zhuǎn)碼為中文的實(shí)例,大家參考使用吧2013-12-12JAVA異常信息Exception?e及e的相關(guān)方法解讀
這篇文章主要介紹了JAVA異常信息Exception?e及e的相關(guān)方法解讀,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06詳解Java如何優(yōu)雅的實(shí)現(xiàn)字典翻譯
當(dāng)我們在Java應(yīng)用程序中需要對字典屬性進(jìn)行轉(zhuǎn)換返回給前端時,如何簡單、方便、并且優(yōu)雅的處理是一個重要問題。在本文中,我們將介紹如何使用Java中的序列化機(jī)制來優(yōu)雅地實(shí)現(xiàn)字典值的翻譯,從而簡化開發(fā)2023-04-04關(guān)于Java跨域Json字符轉(zhuǎn)類對象的方法示例
這篇文章主要給大家介紹了關(guān)于Java跨域Json字符轉(zhuǎn)類對象的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-11-11