如何告诉MapStruct在一个源为空时使用不同的源?

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

How do I tell MapStruct to use a different source if one source is null?

问题

我有两个不同类型的对象,它们映射到第三种类型的对象:

@Mapping(target = "color", source = "color")
public abstract CombinedCar from(BlueBookCar blueBookCar, AutoTraderCar autoTraderCar);
  • CombinedCar 有一个名为 color 的 String 字段。

  • BlueBookCar 有一个名为 color 的 String 字段。

  • AutoTraderCar 有一个名为 carColor 的 String 字段。

如果 BlueBookCarcolor 不为空,我想要使用它来设置 CombinedCar 上的 color

否则,我想要使用 AutoTraderCar 上的 carColor 来设置 CombinedCar 的颜色。

如何配置 MapStruct 来实现这个呢?

英文:

I have two objects of different types that are mapped to an object of a third type:

@Mapping(target = "color" //how to map this )
public abstract CombinedCar from(BlueBookCar blueBookCar , AutoTraderCar autoTraderCar);
  • CombinedCar has a String field named, color.

  • BlueBookCar has a String field named, color.

  • AutoTraderCar has a String field named, carColor.

If BlueBookCar has a non-null color, I want to use it to set the color on CombinedCar.

Otherwise, I want to use the carColor of AutoTraderCar to set the color on CombinedCar.

How can configure MapStruct to do this?

答案1

得分: 2

定义一个@AfterMapping方法,执行逻辑并设置color值:

@Mapper
public abstract class MyMapper {
  @Mapping(target = "color", ignore = true)
  public abstract CombinedCar from(BlueBookCar blueBookCar, AutoTraderCar autoTraderCar);

  @AfterMapping
  public void mapColor(
      @MappingTarget CombinedCar target, BlueBookCar blueBookCar, AutoTraderCar autoTraderCar) {
    target.setColor(
        blueBookCar.getColor() == null ? autoTraderCar.getColor() : blueBookCar.getColor());
  }
}

@Mapping(target = "color", ignore = true) 是为了防止在构建过程中出现以下错误:

java: Several possible source properties for target property "color".

英文:

Define an @AfterMapping method that would do the logic and set the color value:

@Mapper
public abstract class MyMapper {
  @Mapping(target = "color", ignore = true)
  public abstract CombinedCar from(BlueBookCar blueBookCar, AutoTraderCar autoTraderCar);

  @AfterMapping
  public void mapColor(
      @MappingTarget CombinedCar target, BlueBookCar blueBookCar, AutoTraderCar autoTraderCar) {
    target.setColor(
        blueBookCar.getColor() == null ? autoTraderCar.getColor() : blueBookCar.getColor());
  }
}

@Mapping(target = "color", ignore = true) is necessary to prevent error below from appearing during the build.

> java: Several possible source properties for target property "color".

huangapple
  • 本文由 发表于 2023年6月29日 02:35:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76575854.html
匿名

发表评论

匿名网友

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

确定