【问题标题】:ModelMapper Not MappingModelMapper 不映射
【发布时间】:2018-12-13 19:45:10
【问题描述】:

当我尝试通过枚举将源中的字符串映射到目标中的整数时。 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;
}
}

【问题讨论】:

    标签: enums modelmapper


    【解决方案1】:

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

    【讨论】:

    • 谢谢,我写了这个转换器,它可以工作,但问题是,有两个相似的字段。第二个字段是优先级,如果我将优先级映射到另一个枚举。这也使用相同的转换器,并且映射不会正确发生。
    • @Jags,为优先级枚举定义一个新的Converter
    • 谢谢,由于某种原因,这没有按预期工作,但是现在可以工作了。刚刚在 git 中上传了这个简单的项目,所以这可能对其他人有帮助。 github.com/hsjagadeesh/LearningModelMapper
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-27
    • 2019-01-15
    • 1970-01-01
    • 1970-01-01
    • 2015-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多