首页 > 解决方案 > 使用自定义方法为 ModelMapper 定义映射

问题描述

我想使用 org.modelmapper.ModelMapper 将某个实体映射到另一个实体。问题是为了给目标实体设置一些值,我需要根据源实体的值来计算这个值。

我产生了这样的代码:

private TargerEntity convertToTargerEntity( SourceEntity src ) {
    this.modelMapper.typeMap( SourceEntity.class, TargerEntity.class )
            .addMapping( src -> src.getUser().getId(), TargerEntity::setUserId )
            .addMapping( src -> getValueProperty(src), TargerEntity::setEvaluatedValue );

    return this.modelMapper.map( src, TargerEntity.class );
}

负责计算的方法如下:

private String getValueProperty( SourceEntity entity ) {
    return entity.getInformation().stream()
        .filter( property -> Objects.equals( property.getName(), "desiredPropertyValue" ) )
        .findFirst().orElse( null );
}

但是在映射时,我得到一个 org.modelmapper.internal.ErrorsException 没有任何额外的消息。

这种行为的原因是什么?它应该工作吗?

标签: javamodelmapper

解决方案


尝试使用Converter

private TargerEntity convertToTargerEntity(SourceEntity src) {
    Converter<Information, String> converter =
            ctx -> ctx.getSource() == null ? "" : ctx.getSource().stream()
                    .filter(property -> Objects.equals(property.getName(), "desiredPropertyValue"))
                    .findFirst().orElse(null);

    this.modelMapper.typeMap(SourceEntity.class, TargerEntity.class 
            .addMapping(src -> src.getUser().getId(), TargerEntity::setUserId)
            .addMappings(mapper -> mapper.using(converter).map(SourceEntity::getInformation, TargerEntity::setEvaluatedValue));

    return this.modelMapper.map(src, TargerEntity.class);
}

用你的替换Information类型。转换器也可以定义为单例对象。


推荐阅读