java - 使用自定义方法为 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 没有任何额外的消息。
这种行为的原因是什么?它应该工作吗?
解决方案
尝试使用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
类型。转换器也可以定义为单例对象。
推荐阅读
- android - 如何在 android Webview 中播放 html 音频,我需要简单的编码
- python-3.x - Matplotlib:地球绕太阳运行的动画
- php - 从 PHP 中的文本中删除最后一个 URL 链接的表达式
- forms - Tableau - 使用不同变量的 KPI(表单)
- python - 打开 Django 服务器时出现循环导入错误
- java - 带空格的凯撒密码解密方法
- python - 通过聚合每个桶中的不均匀元素进行批处理?
- git - 在 git add 之后,为什么文件被“重命名”?
- react-native - React Native Autocomplete Input 结果列表忽略触摸
- php - 为什么这个 Sylius 资源 API 要求提供模板?