【问题标题】:modelmapper skip nested object's propertiesmodelmapper 跳过嵌套对象的属性
【发布时间】:2016-12-20 06:56:57
【问题描述】:
class A {               class ADto {
   int id;      ->         int id;
   List<B> b;              List<BDto> b;
}                       }   

class B {               class BDto {
   int id;      ->         int id;
   C c;                    CDto c;
}                       }   

在转换A -&gt; ADto 时,我想跳过C -&gt; CDto 的映射。 我的印象是,只要在B -&gt; BDto 之间进行转换,以下映射器就会起作用,但事实并非如此;所以下面的映射器在隐藏(A -&gt; ADto)时没有帮助...

class BMap extends PropertyMap<B, BDto> {
    @Override
    protected void configure() {
        skip(destination.getC());
    }
}

应该如何实现这一目标?

【问题讨论】:

标签: java properties nested skip modelmapper


【解决方案1】:

在这种情况下,您可以有两种不同的选择。

1) 使用带有属性映射 B 到 BD 的 ModelMapper 实例来跳过 c

第一个是为这种特殊情况使用 ModelMapper 实例,在 B -&gt; BDto 映射中添加 PropertyMap 跳过 c。所以你必须添加它:

ModelMapper mapper = new ModelMapper();
mapper.addMappings(new BMap());

2) 创建一个Converter并在A to ADto PropertyMap中使用它

另一个选项是使用转换器,因此在您的情况下,您应该有一个 Converter 来转换 B -&gt; BDto,然后在 A -&gt; ADto PropertyMap 中使用它:

 public class BToBDto implements Converter<B, BDto> {
      @Override
      public BDtoconvert(MappingContext<B, BDto> context) {
          B b = context.getSource();
          BDto bDto = context.getDestination();
         //Skip C progammatically....
         return bDto ;
      }
 }

然后在你的 PropertyMap 中使用转换器:

    class BMap extends PropertyMap<B, BDto> {
          @Override
          protected void configure() {
                using(new BToBDto()).map(source).setC(null);
                //Other mappings...
          }
   }

【讨论】:

  • 您能否详细说明一下,或者举个例子?跳过语句的问题是跳过了对象分配,而是单独分配了所有对象属性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-25
  • 2021-09-27
  • 1970-01-01
相关资源
最近更新 更多