英文:
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 字段。
如果 BlueBookCar 的 color 不为空,我想要使用它来设置 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);
-
CombinedCarhas a String field named,color. -
BlueBookCarhas a String field named,color. -
AutoTraderCarhas 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".
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论