MapStruct将新的计算字段添加到dto [英] MapStruct add a new calculated field to the dto
问题描述
我正在尝试使用MapStruct将实体Order
映射到OrderDTO
.我想在OrderDTO
中添加一个新字段total
,该字段在原始实体Order
中不可用,应使用Order
中的可用信息(订单输入价格,数量,税项)进行计算. ).
我在OrderDTO
中创建了一个新字段total
,我试图通过向映射器界面添加默认方法来映射它:
I'm trying to map an entity Order
to a OrderDTO
using MapStruct. I want to add to OrderDTO
a new field total
, this field is not available in the original entity Order
and should be calculated using the information available in the Order
(order entries price, quantity, taxes...).
I created a new field total
in the OrderDTO
and I'm trying to map it by adding a default method to the mapper interface:
public interface OrderMapper {
...
default BigDecimal orderToTotal(Order order){
return logicToCalculateTotal();
}
}
当我吃午餐时,构建MapStruct会启动错误
When I lunch the build MapStruct launch the error
未映射的目标属性:总计".
Unmapped target property: "total".
有什么办法解决这个问题吗?
Any idea how to solve this problem?
谢谢
推荐答案
有多种方法可以实现您所需要的.第一种方法是使用@AfterMapping
或@BeforeMapping
.如果这样做,您的代码将如下所示:
There are multiple way to achieve what you need. The first way is to use @AfterMapping
or @BeforeMapping
. If you go with this your code will look like:
public interface OrderMapper {
@Mapping(target = "total", ignore = true) // Needed so the warning does not shown, it is mapped in calculateTotal
OrderDto map(Order order);
@AfterMapping // or @BeforeMapping
default void calculateTotal(Order order, @MappingTarget OrderDto dto) {
dto.setTotal(logicToCalculateTotal());
}
}
另一种方法是像开始时那样做,但是必须说total
是从Order
映射的.
The alternative approach would be to do like you started, but you have to say that total
is mapped from the Order
.
您在替代方法中的映射器将是:
Your mapper in the alternative approach would be:
public interface OrderMapper {
@Mapping(target = "total", source = "order")// the source should be equal to the property name
OrderDto map(Order order);
default BigDecimal orderToTotal(Order order) {
return logicToCalculateTotal();
}
}
这篇关于MapStruct将新的计算字段添加到dto的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!