如何防止使用 ModelMapper 在对象内映射空对象?

问题描述 投票:0回答:1

我在 Java 应用程序中使用 ModelMapper 进行对象映射。但是,我遇到了一个问题,源对象内的空对象仍然映射到目标对象。如何配置 ModelMapper 来跳过空对象的映射?

这是我的 dto,

@Getter
@Setter
public class OperationDto extends BaseDto {
    private Long operationNo;
    private EnumOperationType operationType;
    private EnumOperationStatus operationStatus;
    private UserDto driverDto;
    private UserDto operatorDto;
    private VehicleDto vehicleDto;
    private Date startDate;
    private Date endDate;
    private Date targetDate;
    private LocationDto fromLocationDto;
    private LocationDto toLocationDto;
    private String description;


    @Override
    public Object newInstance() {
        OperationDto operationDto = new OperationDto();
        operationDto.setDriverDto(new UserDto());
        operationDto.setOperatorDto(new UserDto());
        operationDto.setVehicleDto(new VehicleDto());
        operationDto.setFromLocationDto(new LocationDto());
        operationDto.setToLocationDto(new LocationDto());
        return operationDto;
    }
}

这是我的尝试,

public List<OperationDto> getAllByFilter(OperationDto filterDto) throws TalyumException {
    OperationDto initializedFilterDto = (OperationDto) new OperationDto().newInstance();

    modelMapper.getConfiguration().setSkipNullEnabled(true);
    modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);        
    initializedFilterDto = modelMapper.map(filterDto, OperationDto.class);

    List<OperationEntity> operationEntityList = operationRepository.findAllByFilter(initializedFilterDto);
    return operationEntityList.stream().map(dto -> modelMapper.map(dto, OperationDto.class)).toList();
}

如有任何帮助,我们将不胜感激。

java spring modelmapper
1个回答
0
投票

你可以这样尝试吗

modelMapper.getConfiguration().setPropertyCondition(Conditions.isNotNull());

设置此配置后,它应该可以工作,尽管我不确切知道如何在代码中注入模型映射器。

© www.soinside.com 2019 - 2024. All rights reserved.