本文主要是介绍MapStruct高级用法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
MapStruct高级用法
-
依赖注入(Using dependency injection)
@Mapper(componentModel = SPRING) public interface SpringMapper {SpringMapper MAPPER = Mappers.getMapper(SpringMapper.class);PersonDTO personDoToDTO(Person person); }
public static final class ComponentModel {private ComponentModel() {}public static final String DEFAULT = "default";public static final String CDI = "cdi";public static final String SPRING = "spring";public static final String JSR330 = "jsr330";public static final String JAKARTA = "jakarta"; }
示例代码:
com.yxxmg.mapstruct.convert.SpringMapper
-
组合多个映射
@Mapper(imports = Date.class) public interface PersonMapper {PersonMapper MAPPER = Mappers.getMapper(PersonMapper.class);@Mapping(target = "personName", source = "name")@Mapping(target = "id", ignore = true)// 忽略id,不进行映射PersonDTO personDoToDTO(Person person);@Mapping(target = "personName", source = "name") // 指定映射@Mapping(target = "describe", source = "describe", defaultValue = "默认值") // 设置默认值@Mapping(target = "updateDate", expression = "java(new java.util.Date())") // 表达式 java@Mapping(target = "modifyDate", expression = "java(new Date())")@Mapping(target = "createDate", source = "createTime", dateFormat = "YYYY-MM-DD") // 格式化@Mapping(source = "source", target = "source", numberFormat = "#0.00")PersonDTO convert2(Person person); }
示例代码:
com.yxxmg.mapstruct.convert.PersonMapper
-
嵌套对象属性映射
@Mapperpublic interface CustomerMapper {@Mapping( target = "name", source = "record.name" )@Mapping( target = ".", source = "record" )@Mapping( target = ".", source = "account" )Customer customerDtoToCustomer(CustomerDto customerDto);}
-
迭代器以及参数传递
使用
@IterableMapping
、@Context
@Mapper public interface MenuMapper {MenuMapper MAPPER = Mappers.getMapper(MenuMapper.class);@Mapping(target = "parentId", source = "parentId")Menu convert(String parentId, MenuDTO menuDTO);@IterableMapping(qualifiedByName = "convertDTO")List<Menu> convert(@Context String parentId, List<MenuDTO> menuDTOList);@Named("convertDTO")default Menu convertDTO(@Context String parentId, MenuDTO menuDTO) {return convert(parentId, menuDTO);}
示例代码:
com.yxxmg.mapstruct.convert.MenuMapper
-
隐式转换
例如可以定义默认方法将枚举转换成字符串或者数值,所有枚举字段会自动隐式转换,上述的例子中已经体现,就不举例说明
-
映射参数到目标对象上
@MappingTarget
@Mapper public interface SourceTargetMapper {SourceTargetMapper MAPPER = Mappers.getMapper(SourceTargetMapper.class);void toEntity(ParentDto s, @MappingTarget ParentEntity t);@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE)interface LenientMapper {void toEntity(ChildDto s, @MappingTarget ChildEntity t);} }
示例代码:
com.yxxmg.mapstruct.mappingtarget.SourceTargetMapper
-
后续发现其他高级特性待补充…
示例代码相关地址
https://gitee.com/youxiaxiaomage/java-practices
这篇关于MapStruct高级用法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!