如何配置模型映射器以跳过目标中的嵌套属性

问题描述 投票:0回答:2
Source{
String one;
String two;
}

Destination{
String one;
Child child;
}

Child{
String two;
}

main() {
ModelMapper modelMapper = new ModelMapper();
// what configurations to set here?
Source source = new Source("one=1", "two=2");
Destination desiredResult = new Destination();
desiredResult.setOne("one=1");
Destination mappedResult = modelmapper.map(source, Destination.class )
assertEquals(mappedResult,  desiredResult );
}

问题是 modelmapper 将映射

source.two => destination.child.two
,这是我不想要的。我尝试过类似的方法

1. modelMapper.getConfiguration().setPreferNestedProperties(false);
2. modelMapper.getConfiguration().setAmbiguityIgnored(true);
3. modelMapper.getConfiguration().setImplicitMappingEnabled(false);
4. modelMapper.addMappings(new PropertyMap<Source, Destination>() {
      @Override
      protected void configure() {
        skip(destination.getChild());
        skip(destination.getChild().getTwo());
      }
    });

没有任何效果。

我希望有一个通用的解决方案,可以阻止模型映射器映射目标对象中的任何嵌套对象的属性。

java modelmapper
2个回答
2
投票

您是否可能缺少一些预先存在的配置?你的例子对我来说效果很好。

无论如何,这种事情大多发生在你使用

LOOSE
匹配策略时。

modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.LOOSE);

您可以通过将匹配策略显式设置为

STANDARD
STRICT
来修复此问题。

modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STANDARD);

或者

modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);

查看文档以获取有关匹配策略、命名约定、默认配置等的更多信息。


0
投票

我也有类似的问题。我需要从 DTO 填充一个 Hibernate 实体。该实体具有嵌套属性,这是一个非常复杂的具有循环关系的实体。 DTO 没有该属性的相同数据,因此我可以稍后在持久化实体之前手动填充它。所以我只是对该字段使用skip().setProperty(null),但ModelMapper仍在为其创建映射。这不是什么大问题,因为该值被忽略,但我也有单元测试,需要调用 modelMapper.validate() 方法来验证所有映射是否正确并且没有丢失任何属性。我使用严格策略,但它无助于避免验证问题。唯一的解决方案是设置此配置:modelMapper.getConfiguration().setPreferNestedProperties(false)。它解决了验证问题,但现在我必须手动映射嵌套属性,这使得 ModelMapper 几乎毫无用处。 ModelMapper 中可能存在错误,理想情况下,当您将属性标记为跳过映射时,它不应创建嵌套属性的完整映射,也不应验证标记为跳过的冗余映射。

© www.soinside.com 2019 - 2024. All rights reserved.