MapStruct add a new calculated field to the dto

ぐ巨炮叔叔 提交于 2020-12-30 08:25:29

问题


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();
    }
}

When I lunch the build MapStruct launch the error

Unmapped target property: "total".

Any idea how to solve this problem?

Thanks


回答1:


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());
    }
}

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();
    }
}



回答2:


if the calculated field can be completely calculated by using other fields in DTO:

I would put these calculations into getMethods - no need to add redundant fields. (Thinking about tight cohesion)

If you name the method getTotal it will be seen in json/xml with name "total" besides all other fields.



来源:https://stackoverflow.com/questions/45500779/mapstruct-add-a-new-calculated-field-to-the-dto

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!