如果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中做。整个问题是答案是由两个映射器组合而成的,而我没有成功地实现这一点。
@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;
...
}
一个简单的解决方案是在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);
}
}