ModelMapper mapper.skip()不适用于具有循环依赖关系的pojo对象

时间:2018-05-24 14:27:26

标签: pojo modelmapper typemaps

我有两个pojo对象:HusbandWife相互引用。

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
}

我为两个对象创建了简单的typeMap规则,其中跳过了引用的对象。

我的测试班:

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

}

updatedHusband映射到husband时,不会跳过setWife()方法。但是,如果我从modelMapper中删除typeWife映射,则代码可以正常工作。

我正在使用ModelMapper 1.1.3

感谢。

编辑: 我认为问题在于模型映射器生成的映射。当我打印每个typeMap的映射时,这就是我得到的:

[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在映射过程中从typeWife选择映射。

1 个答案:

答案 0 :(得分:1)

问题是v2.1.0中的fixed。 感谢开发人员的出色工作!