MapStruct入门使用

MapStruct入门使用案例

以下是常用的使用举例,按照需求改动即可

java 复制代码
@Data
public class UserDO{
    private int age;
    private String name;
    private Role role;
    private String date;
}


@Data
public class UserDTO{
    private int dtoAge;
    private String dtoName;
    private Guest guest;
    private Date date;
}
java 复制代码
import org.mapstruct.*;
import org.mapstruct.factory.Mappers;


@Mapper
public interface UserConvert{
    
    UserConvert INSTANCE = Mappers.getMapper(UserConvert.class);
    
    //方式1 返回值的方式
    UserDO  DTOConvertDO(UserDTO dto);
    
    //方式2 参数加注解的方式
    void DTOConvertDO(UserDTO dto,@MappingTarget UserDO user)
     
    //自动忽略源对象为空的值
    @BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
    UserDO  DTOConvertDO(UserDTO dto);
        
    //resultType 指定返回目标类型,ignoreByDefault = true:在目标类型CarDto中忽略所有未映射的属性。
    //mappingControl = MappingControl.FILTER:如果存在未匹配的属性,过滤它们而不报告错误或警
    @BeanMapping(resultType = UserDO.class,ignoreByDefault = true, mappingControl = MappingControl.FILTER)    	  UserDO  DTOConvertDO(UserDTO dto);
        
    //非同名属性之间映射,指定dto的dtoName映射到Do中的name中
    @Mapping(source = "dtoName",target = "name")
    //条件映射,大于18岁进行映射赋值    
    @Mapping(condition = "java(dto.getDtoAge() >= 18)", target = "age")
    //忽略指定值映射    
    @Mapping(source="guest",ignore=true)    
    void DTOConvertDO(UserDTO dto,@MappingTarget UserDO user)
        
    //非同名属性之间映射,包含其下的二层对象属性的赋值。dateFotmat指定时间格式
    @Mappings({
        @Mapping(source = "dtoName",target = "name"),
        @Mapping(source = "dtoAge",target = "age")
        @Mapping(source = "guest.name",target = "role.name")
        @Mapping(source = "date",target = "date",dateFotmat="yyyy-MM-dd")
    })
   void DTOConvertDO(UserDTO dto,@MappingTarget UserDO user)
        
   // 当为 null 时不赋值,可以一个个设置
   @Mapping(target = "dtoName", source = "name", defaultExpression = "java(null)")
   void DTOConvertDO(UserDTO dto,@MappingTarget UserDO user) 
        
        
   //集合映射
   @MapMapping(valueDateFormat="yyyy-MM-dd")
   void DTOConvertDO(Map<String,Date> dto,@MappingTarget Map<String,String> map)      
}

注解作用:

@BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE) : 忽略为null值的映射赋值

@MappingTarget : 指定赋值目标对象,赋值到哪去。

@Mapping(source = "dtoName",target = "name") : 指定映射关系,不同名的属性赋值,UserDTO下的dtoName赋值到UserDO下的name

@Mappings({

@Mapping(source = "dtoName",target = "name"),

@Mapping(source = "dtoAge",target = "age")

}) : 指定映射关系,多个时。