ModelMapper不映射

时间:2018-12-12 23:45:17

标签: enums modelmapper

当我尝试通过Enum将源中的String映射到Destination中的Integer时。 ModelMapper失败。

来源

public class Request {
    private String classification;
}

目的地

public class DTO {
    private Integer classification;
}

字符串和整数之间的映射是在ENUM中定义的

public enum Classification {

POWER(3, "Power"),
PERFORMANCE(4, "Performance"),
TASK(13, "Task");

private final Integer code;
private final String  name;

ProblemClassification(final int code, final String name) {
    this.code = code;
    this.name = name;
}

public Integer getCode() {
    return code;
}

public String getName() {
    return name;
}

public static Integer getCodeByName(String name) {
    Optional<Classification> classification = Arrays.asList(Classification.values()).stream()
            .filter(item -> item.getName().equalsIgnoreCase(name))
            .findFirst();
    return classification.isPresent() ? classification.get().getCode() : null;
}
}

1 个答案:

答案 0 :(得分:0)

您需要在这里Converter

ModelMapper modelMapper = new ModelMapper();
Converter<String, Integer> classificationConverter =
                ctx -> ctx.getSource() == null ? null : Classification.getCodeByName(ctx.getSource());
modelMapper.typeMap(Request.class, DTO.class)
                .addMappings(mapper -> mapper.using(classificationConverter).map(Request::getClassification, DTO::setClassification));