使用生成的类通过MapStruct在两个映射器之间传输对象

huangapple go评论77阅读模式
英文:

Transferring Object with MapStruct via 2 Mappers using Generated Class

问题

  • 我有3个类:A,B,C。
  • 每个类都有一个ObjectX字段。
  • 类A和C还有一个ObjectY字段。
  • 类B是自动生成的,我无法修改它。
  • 我有从A到B的映射器,以及从B到C的映射器,它们都不包括ObjectY(它被忽略)。

是否有可能以某种方式修改这些映射器,以便包括ObjectY(而无需添加从A到C的映射)?

映射器代码如下:

@Mapper
public interface MyMapper {
  @Mapping(target = "ObjectX")
  B AtoB(A a);

  @Mapping(target = "ObjectX")
  C BtoC(B b);
}
英文:
  • I have 3 Classes: A, B, C.
  • Each of them has single ObjectX field.
  • Classes A and C have also ObjectY field.
  • Class B is auto-generated, I can't modify it.
  • I have mapper from A to B, and mapper from B to C, they don't
    include ObjectY (it is ignored).

Is it possible somehow to modify these mappers in order to include ObjectY (without adding mapping between A to C)?

mapper code is below:

@Mapper
public interface MyMapper {
@Mapping(target = "ObjectX")
  B AtoB(A a);

@Mapping(target = "ObjectX")
  C BtoC(B b);
}

答案1

得分: 1

如果我理解问题正确,您想将 A 转换为 B,然后将 B 转换为 C,并且您还想保留 ObjectY 字段。
问题在于 B 没有 ObjectY 字段,因此无法通过此转换来存储其值。

我脑海中浮现的唯一解决方案是创建一个类 MyB,它继承自类 B,并包含 ObjectY 字段,然后像这样更改您的映射器:

public class MyB extends B {
    private ObjectY objectY;
    // 为简洁起见省略了 getter 和 setter 方法
}
@Mapper
public interface MyMapper {
    MyB AtoB(A a);

    C BtoC(MyB b);
}

但我不确定在您的用例中是否可行。

英文:

If I understand the question correctly, you want to translate A to B and then B to C and you also want to keep ObjectY field.
The problem is that B don't have the ObjectY field, so it cannot store the value of it through this translation.

Only solution which comes to my mind is to create class MyB which extends class B and contains ObjectY field and then change your mapper like this:

public class MyB extends B {
    private ObjectY objectY;
    // getters and setters omitted for brevity
}
@Mapper
public interface MyMapper {
    MyB AtoB(A a);

    C BtoC(MyB b);
}

But I'm not sure if it is possible in your use case.

huangapple
  • 本文由 发表于 2020年3月16日 01:03:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/60695467.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定