【问题标题】:MapStruct add a new calculated field to the dtoMapStruct 向 dto 添加一个新的计算字段
【发布时间】:2020-11-24 21:49:30
【问题描述】:

我正在尝试使用 MapStruct 将实体 Order 映射到 OrderDTO。我想在OrderDTO 中添加一个新字段total,该字段在原始实体Order 中不可用,应使用Order 中可用的信息计算(订单条目价格、数量、税金.. .)。 我在OrderDTO 中创建了一个新字段total,并尝试通过向映射器接口添加默认方法来映射它:

public interface OrderMapper {

    ...

    default BigDecimal orderToTotal(Order order){
        return logicToCalculateTotal();
    }
}

当我午餐时构建 MapStruct 启动错误

未映射的目标属性:“total”。

知道如何解决这个问题吗?

谢谢

【问题讨论】:

    标签: spring-boot java-8 mapstruct


    【解决方案1】:

    有多种方法可以实现您的需求。第一种方法是使用@AfterMapping@BeforeMapping。如果您使用此代码,您的代码将如下所示:

    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 映射的。

    您在替代方法中的映射器将是:

    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】:

      如果计算的字段可以完全用DTO中的其他字段计算:

      我会将这些计算放入 getMethods - 无需添加冗余字段。 (想想tight cohesion

      如果您将方法命名为 getTotal,它将在 json/xml 中看到,除所有其他字段外,名称为“total”。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-18
        • 1970-01-01
        • 1970-01-01
        • 2017-12-23
        • 2016-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多