java Mapstruct:按条件Map

u3r8eeie  于 2023-01-01  发布在  Java
关注(0)|答案(1)|浏览(171)

如果shipping.status==Status.Opened,我应该将ShipmentResponseDto.cargo.packaging.lastMeasurements中的几个字段返回为null,如下所示:

if(shipment.status=Status.Opened){
   ShipmentResponseDto.cargo.packaging.lastMeasurements.firstField = null;
   ShipmentResponseDto.cargo.packaging.lastMeasurements.secondField = null;
}

我想在mapstruct中完成,整个问题是答案是由两个Map器组装而成的,我没有成功地实现这一点。

@Mapper(uses = {
    CargoPackagingMapper.class
})
public interface ShipmentMapper extends BasicMapper<ShipmentResponseDto, Shipment> {

}

@Mapper(uses = {PackagingTypeMapper.class})
public abstract class CargoPackagingMapper implements BasicMapper<CargoPackagingResponseDto, Packaging> {

    @Override
    @Mappings(...)
    public abstract CargoPackagingResponseDto toDto(Packaging source);
}

public class Shipment {

    ...
    ...
   @Enumerated(EnumType.STRING)
    private Status status;
    private Set<ShipmentCargo> cargo = new HashSet<>();
    ...
}

public class ShipmentCargo {
    ...
    @ManyToOne
    private Packaging packaging;
    ...

}
public class Packaging {
    ...
    
    private PackagingLastMeasurements lastMeasurements;
    ...

}
xe55xuns

xe55xuns1#

一个简单的解决方案是在ShipmentMapper中定义@AfterMapping方法,将这些字段设置为null,如下所示:

@AfterMapping
default void setFieldsToNullIfStatusIsOpen(Shipment shipment, @MappingTarget ShipmentResponseDto response) {
  if(shipment.getStatus()==Status.Opened){
    PackagingLastMeasurements plm = response.getCargo().getPackaging().getLastMeasurements();
    plm.setFirstField(null);
    plm.setSecondField(null);
  }
}

相关问题