介绍
官方参考:https://mapstruct.org/documentation/stable/reference/html/
mapstruct 用于将一个对象和另外一个对象进行映射,避免大量的手工作业,比如:PO对象转换为DTO对象
简单使用
PO转DTO和DTO转PO
@Mapper(componentModel = "spring")
public interface UserConverter {
List<UserDTO> toDto (List<UserPO> items);
UserDTO toDto (UserPO item);
List<UserPO> toPo (List<UserDTO> items);
UserPO toPo (UserDTO item);
}
Mapping
上述转换目标对象会产生新对象,假如我们给现有对象赋值,我们怎么做呢
增加MappingTarget注解
@Mapper(componentModel = "spring")
public interface UserConverter {
UserDTO toDto (UserPO item, @MappingTarget UserDTO dto);
UserPO toPo (UserDTO item, @MappingTarget UserPO po);
}
跳过NULL
如果为null,不做替换,需要怎么做?
增加 nullValuePropertyMappingStrategy 类型
@Mapper(componentModel = "spring", nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
public interface UserConverter {
UserDTO toDto (UserPO item, @MappingTarget UserDTO dto);
UserPO toPo (UserDTO item, @MappingTarget UserPO po);
}