java 推土机映射:多个源到目的地

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15519547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 19:54:27  来源:igfitidea点击:

Dozer mapping : More than one source to destination

javadozer

提问by VinayVeluri

Im new to DOZER mapping

我是 DOZER 映射的新手

Can we map properties from more than one source class to destination?

我们可以将属性从多个源类映射到目标吗?

EG

例如

class A {
          int a;
          int b;
}

class B {
    String c;
}

class Destination {
    int a;
    int b;
    String c;
}

Can it be possible to do this with one mappings configuration file ?

可以用一个映射配置文件来做到这一点吗?

采纳答案by Perception

Not directly no. You would need to either create a new class to wrap around your two source classes and copy from that:

不是直接没有。您需要创建一个新类来包装您的两个源类并从中复制:

class D {
    private A a;
    private B b;
}

<mapping>
  <class-a>D</class-a>
  <class-b>C</class-b>
  <field>
    <a>a.a</a>
    <b>a</b>
  </field>
  <field>
    <a>a.b</a>
    <b>b</b>
  </field>
  <field>
    <a>b.c</a>
    <b>c</b>
  </field>
</mapping>

Or you would need to copy twice, once from each source class to the destination object, making sure not to blank out existing fields.

或者您需要复制两次,一次从每个源类复制到目标对象,确保不要清空现有字段。

<mapping wildcard="false">
    <class-a>A</class-a>
    <class-b>C/class-b>
    <field>
       <a>a</a>
       <b>a</b>
    </field>   
    <field>
       <a>b</a>
       <b>b</b>
    </field>   
</mapping>

<mapping wildcard="false">
    <class-a>B</class-a>
    <class-b>C/class-b>
    <field>
       <a>c</a>
       <b>c</b>
    </field> 
</mapping>

回答by Holgzn

You can just map twice. First, use Destination.class as target, then use the Object that resulted from the first mapping as target:

你可以只映射两次。首先,使用 Destination.class 作为目标,然后使用第一次映射产生的 Object 作为目标:

    A a = new A();
    a.setA(1);
    a.setB(2);

    B b = new B();
    b.setC("3");

    Mapper mapper = DozerBeanMapperSingletonWrapper.getInstance();

    Destination destination = mapper.map(a, Destination.class);

    mapper.map(b, destination);

    System.out.println(destination);
    // Destination [a=1, b=2, c=3]

This even works with an empty mapping configuration file.

这甚至适用于空的映射配置文件。