我正在尝试使用 mapstruct 1.2.0.CR2 映射嵌套属性。 (示例映射 customer.address.houseNumber 到 userDTO.homeDTO.addressDTO.houseNo )。
期望:当customer.address为null时,我不想将addressDTO设置为null。由于 addressDTO 包含“countyname”和其他已从其他不同来源设置的属性。
请告知我是否可以设置某些属性/设置,以便当源为空时目标不会设置为空。
@Mapper( nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS )
public interface CustomerUserMapperNullCheck {
@Mapping(source="address", target="homeDTO.addressDTO" )
void mapCustomer(Customer customer, @MappingTarget UserDTO userDTO) ;
@Mapping(source="houseNumber", target="houseNo" )
void mapCustomerHouse(Address address, @MappingTarget AddressDTO addrDTO) ;
}
我最初尝试使用如下所示的单一映射
@Mapping(target="homeDTO.addressDTO.houseNo", source="address.houseNumber")
abstract void mapCustomerHouse(Customer customer, @MappingTarget UserDTO userDTO) ;
然后尝试基于 https://github.com/mapstruct/mapstruct/issues/649 拆分映射。
两种方法都没有产生预期的结果/ 生成的方法代码
protected void customerToHomeDTO(Customer customer, HomeDTO mappingTarget) {
if ( customer == null ) {
return;
}
if ( customer.getAddress() != null ) {
if ( mappingTarget.getAddressDTO() == null ) {
mappingTarget.setAddressDTO( new AddressDTO() );
}
mapCustomerHouse( customer.getAddress(), mappingTarget.getAddressDTO() );
}
**else {
mappingTarget.setAddressDTO( null ); // I dont want to else where addressDTO is set to null.
}**
}
完整生成的代码在这里
https://github.com/mapstruct/mapstruct/issues/1306
谢谢
@Mapper( nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE )
对我来说只有这个有效,如下所述:https://github.com/mapstruct/mapstruct/issues/649
@Mapper( nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS )
对我来说,它是这样工作的:
@Mapper(nullValueMappingStrategy = NullValueMappingStrategy.RETURN_DEFAULT)
public interface MyMapper {
...
}
这对我有用:
@BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
void updateProduct(@MappingTarget Product entity, ProductRequestDto dto);
@Mapping 注释在当前(1.5.5.Final)MapStruct 版本中需要“target”选项。
感谢 github 讨论上的 @tak3shi 链接!
我正在使用 Mapstruct
1.5.5.Final
您可以在映射器级别使用
NullValuePropertyMappingStrategy.IGNORE
来影响所有映射方法:
@Mapper(
nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE
)
public interface MyMapper {..}
如果您只想覆盖单个值的映射,您可以在映射级别使用
NullValuePropertyMappingStrategy.IGNORE
并定义自定义映射方法:
@Mappings({
@Mapping(target = "json", source = "json",
qualifiedByName = "jsonCustomMapper",
nullValueCheckStrategy = NullValueCheckStrategy.ON_IMPLICIT_CONVERSION)
})
Target target(Source source);
...
@Named("jsonCustomMapper")
default String jsonCustomMapper(String json) {
// Define empty json for null or empty json string
return (json == null || json.trim().isEmpty()) ? "{}" :json;
}
请注意,
ON_IMPLICIT_CONVERSION
不影响自定义映射方法。
https://mapstruct.org/documentation/stable/api/org/mapstruct/NullValueCheckStrategy.html#ON_IMPLICIT_CONVERSION
希望这对您有用。