pojomodelmappertypemaps

ModelMapper mapper.skip() doesn't work for pojo objects with circular dependency


I have two pojo objects: Husband, Wife which reference each other.

Husband.java

public class Husband {
   private String name;
   private int age;
   private String man;
   private Wife wife;

   // getter, setter, builder, constructor are removed for berevity
}

Wife.java

public class Wife {
   private String name;
   private int age;
   private String woman;
   private Husband husband;

   // getter, setter, builder, constructor are removed for berevity
}

I've created simple typeMap rulings for both objects, where the referenced object is skipped.

My test class:

public class ModelTest {

@Test
public void test() {
    ModelMapper modelMapper = new ModelMapper();
    TypeMap<Wife, Wife> typeWife = modelMapper.createTypeMap(Wife.class, Wife.class);
    typeWife.addMappings(mapper -> {
        mapper.skip(Wife::setHusband);
    });

    TypeMap<Husband, Husband> typeHusband = modelMapper.createTypeMap(Husband.class, Husband.class);
    typeHusband.addMappings(mapper -> {
        mapper.skip(Husband::setWife);
    });

    Wife wife = Wife.builder().age(25).name("Sarah").woman("good woman").build();
    Husband husband = Husband.builder().age(28).name("Imtiaz").man("good man").build();
    wife.setHusband(husband);
    husband.setWife(wife);

    Husband updatedHusband = Husband.builder().age(28).name("Imtiaz Shakil").man("slightly good man").build();
    modelMapper.map(updatedHusband, husband);
    System.out.println(husband.toString());
    System.out.println(husband.getWife().toString());
    }

}

When mapping updatedHusband to husband, setWife() method is not skipped. But, if we I remove typeWife mapping from modelMapper the code works fine.

I'm using ModelMapper 1.1.3

Thanks.

Edit: I think the problem is with the mappings modelmapper generates. When I print the mappings of each typeMap this is what I get:

[PropertyMapping[Wife.age -> Wife.age], PropertyMapping[ -> Wife.husband], PropertyMapping[Wife.name -> Wife.name], PropertyMapping[Wife.woman -> Wife.woman]]
[PropertyMapping[Husband.age -> Husband.age], PropertyMapping[Husband.man -> Husband.man], PropertyMapping[Husband.name -> Husband.name], PropertyMapping[ -> Husband.wife], PropertyMapping[Husband.wife.age -> Husband.wife.age], PropertyMapping[Husband.wife -> Husband.wife.husband], PropertyMapping[Husband.wife.name -> Husband.wife.name], PropertyMapping[Husband.wife.woman -> Husband.wife.woman]]

TypeMap typeHusband picks mapping from typeWife during mapping process.


Solution

  • The problem is fixed in v2.1.0. Thanks to the developers for their great work!