条件时如何使用ModelMapper

时间:2018-06-20 17:28:05

标签: java modelmapper

我在严格模式下使用ModelMapper

public class Student {
    private String fullName;
    private Address address ;
}

public class StudentDto {
    private String fullName;
    private String street;
    private String city;
}

public class Address {
    private String street;
    private String city;
}

地图(来源:学生到目的地:StudentDto)

为了在地址为空时不进行映射,我在以下条件下设置了

Condition<Student, StudentDto> conditionAddressIsNull = new Condition<Student, StudentDto>() {
    public boolean applies(MappingContext<Student, StudentDto> context) {
        return context.getSource().getAddress() == null;
    }
};

PropertyMap<Student, StudentDto> propertryMapToStudentDto = new PropertyMap<Student, StudentDto>() {
    protected void configure() {
        when(conditionAddressIsNull).map(source).setStreet(null);
        when(conditionAddressIsNull).map(source).setCity(null);
    }
};

问题是:即使地址不为空,我也可以获得等于空的街道和城市 如何使用STRICT映射修复该问题

1 个答案:

答案 0 :(得分:0)

您应该when(**conditionAddressIsNotNull**)而不是when(**conditionAddressIsNull**)

when(condition).map()的意思是:当condition = true时,我们进行映射;否则,我们跳过。

我建议您可以尝试

PropertyMap<Student, StudentDto> propertryMapToStudentDto = new PropertyMap<Student, StudentDto>() {
    protected void configure() {
        when(conditionAddressIsNotNull).map().setStreet(source.getAddress().geStreet());
        when(conditionAddressIsNotNull).map().setCity(source.getAddress().getCity());
    }
};