Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java ModelMapper—展平对象的简单方法_Java_Modelmapper - Fatal编程技术网

Java ModelMapper—展平对象的简单方法

Java ModelMapper—展平对象的简单方法,java,modelmapper,Java,Modelmapper,我有一个结构如下的源对象: class SourceA { int www; SourceB sourceB; } class SourceB { int xxx; int yyy; int zzz; } ModelMapper mapper = new ModelMapper(); mapper.createTypeMap(SourceB.class, Dest.class) .addMapping(SourceB::getXxx, Dest::setAaa)

我有一个结构如下的源对象:

class SourceA {
  int www;
  SourceB sourceB;
}

class SourceB {
  int xxx;
  int yyy;
  int zzz;
}
ModelMapper mapper = new ModelMapper();

mapper.createTypeMap(SourceB.class, Dest.class)
  .addMapping(SourceB::getXxx, Dest::setAaa)
  .addMapping(SourceB::getYyy, Dest::setBbb)
  .addMapping(SourceB::getZzz, Dest::setCcc);

mapper.createTypeMap(SourceA.class, Dest.class)
  .addMapping(SourceA::getWww, Dest::setDdd)
  .addMapping(SourceA::getSourceB, ???); // How to reference self here?

目的地:

class Dest {
  int aaa;
  int bbb;
  int ccc;
  int ddd;
}
这是配置映射最直接的方法:

ModelMapper mapper = new ModelMapper();

mapper.createTypeMap(SourceA.class, Dest.class)
  .addMapping(SourceA::getWww, Dest::setDdd)
  .addMapping(src -> src.getSourceB().getXxx(), Dest::setAaa)
  .addMapping(src -> src.getSourceB().getYyy(), Dest::setBbb)
  .addMapping(src -> src.getSourceB().getZzz(), Dest::setCcc);
但我想这样做:

class SourceA {
  int www;
  SourceB sourceB;
}

class SourceB {
  int xxx;
  int yyy;
  int zzz;
}
ModelMapper mapper = new ModelMapper();

mapper.createTypeMap(SourceB.class, Dest.class)
  .addMapping(SourceB::getXxx, Dest::setAaa)
  .addMapping(SourceB::getYyy, Dest::setBbb)
  .addMapping(SourceB::getZzz, Dest::setCcc);

mapper.createTypeMap(SourceA.class, Dest.class)
  .addMapping(SourceA::getWww, Dest::setDdd)
  .addMapping(SourceA::getSourceB, ???); // How to reference self here?

只需一步即可将SourceA转换为Dest,如第一个选项所示:

Dest dest = mapper.map(sourceA, Dest.class);
显然,这是一个过于简化的示例,我的问题是创建一个映射,在这个映射中,我可以引用另一个映射到根dest对象

  • 显式映射
    • 转换嵌套类并创建部分映射的目标对象
    • 映射上一个目标对象上的剩余值
  • 隐式映射,您可以使用以下解决方法之一
    • 将setter添加到目标对象以匹配源字段
    • 或更改目标或源字段名称以相互匹配
    然后使用以下配置和映射

    ModelMapper modelMapper = new ModelMapper();
    
    modelMapper.getConfiguration()
                .setMatchingStrategy(MatchingStrategies.LOOSE);
    
    dest = modelMapper.map(sourceA, Dest.class);
    
    System.out.println(dest);
    
    输出

    Dest{aaa=1, bbb=2, ccc=3, ddd=4}
    

    实际上我就是这样做的,但我正在寻找一种方法,在完成正确的配置后,只需一步就可以实现映射。我将更新问题以澄清这一点。@Vinicius我已添加更新。不是很漂亮,但希望能有帮助!这是一个很好的建议,但我想统一MM配置的转换。