mapStruct 使用踩坑指南

346 阅读1分钟

一、缓存机制

经常因为变更字段(通常会这样),导致启动失败。需要清理生成的文件。

/Users/uzong/IdeaProjects/uzong-crm/uzong-crm-manager/src/main/java/com/uzong/crm/manager/GroupManager.java:14:67
java: 找不到符号
  符号:   方法 getId()
  位置: 类型为com.uzong.crm.infra.database.idto.customerIdTO的变量 existsGroup

如果是 maven 管理。需要执行 maven clean

如果使用热部署插件,执行重新加载的时候,也需要执行 maven clean ,让缓存失效。

二、基础类型定制方法慎用

基础类型定义了一个特殊方法。当 customerId(long) 为0的时候,转换成null。

default String mapCustomerId(Long customerId) {
    return customerId != null && customerId != 0L ? String.valueOf(customerId) : null;
}

然后在 mapping 中使用

@Mappings({
        @Mapping(target = "customerId", expression = "java(mapCustomerId(mdto.getcustomerId()))")
})
CustomerVO mdtoToVO(CustomerMDTO mdto);

最终效果:

所有 Long 类型的字段,都采用了这个方法。影响面被大大扩大!

比如:long 类型在执行映射的时候也采用了这个方法

customerVO.setId( mapCustomerId( mdto.getId() ) );

三、Long类型默认值 0

CustomerCreateParam createRequestToParam(CustomerCreateRequest request);
@Mappings({
        @Mapping(source = "customerId", target = "customerId", defaultValue = "0L")
})
CustomerUpdateParam updateRequestToParam(CustomerUpdateRequest request);

会生成代码:

Long.parseLong( request.getcustomerId() )

但执行代码会报错

Exception in thread "main" java.lang.NumberFormatException: For input string: "0L"
        at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
        at java.lang.Long.parseLong(Long.java:589)
        at java.lang.Long.parseLong(Long.java:631)

如果设置 0,编译通不过!

/Users/uzong/IdeaProjects/uzong-crm/uzong-crm-web/src/main/java/com/uzong/crm/web/converter/CustomerEndPointConverter.java:56:25
java: Can't map "0" to "Long customerId". Reason: L/l mandatory for long types.

目前是踩过的一些坑,后续可以继续补充。