ModelMapper 不映射

ModelMapper Not Mapping

当我尝试通过枚举将源中的字符串映射到目标中的整数时。 ModelMapper 失败。

来源

public class Request {
    private String classification;
}

目的地

public class DTO {
    private Integer classification;
}

String 和 Integer 之间的映射在 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;
}
}

你需要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));