我想使用 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 ,没有任何其他消息。
造成这种行为的原因是什么?它应该有效吗?
最佳答案
尝试使用转换器
:
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
类型替换为您的类型。转换器也可以定义为 Singleton 对象。
关于java - 使用自定义方法为 ModelMapper 定义映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50951458/