modelmapper skip nested object's properties

8.4k views Asked by At
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;
}                       }   

While converting A -> ADto, I want to skip mapping of C -> CDto. I was under the impression the following mapper would work whenever there is conversion between B -> BDto, which doesn't seem to be the case; so the following mapper didn't help while coverting (A -> ADto)...

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

What should be the way to achieve this?

1

There are 1 answers

1
Pau On

In this case you could have two different options.

1) Use a ModelMapper instance with a Property Map B to BDto skiping c

The first one is use a ModelMapper instance for this special case which adding the PropertyMap skiping c in B -> BDto mapping. So you must add it:

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

2) Create a Converter and use it in A to ADto PropertyMap

The other option is using a converter, so in your case you should has a Converter to convert B -> BDto and then in the A -> ADto PropertyMap use it:

 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 ;
      }
 }

Then use the Converter in your PropertyMap:

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