mapStruct 使用踩坑指南

一、缓存机制

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

css 复制代码
/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。

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

然后在 mapping 中使用

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

最终效果:

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

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

less 复制代码
customerVO.setId( mapCustomerId( mdto.getId() ) );

三、Long类型默认值 0

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

会生成代码:

kotlin 复制代码
Long.parseLong( request.getcustomerId() )

但执行代码会报错

php 复制代码
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,编译通不过!

arduino 复制代码
/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.

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

相关推荐
晨曦中的暮雨7 小时前
限流算法——固定窗口、滑动窗口、漏桶、令牌桶
java·开发语言·算法
喵了几个咪8 小时前
GoWind CMS 拆解:在 Go 里给 TipTap 搭一套 Yjs 协同后端
开发语言·后端·golang
Flynt8 小时前
我把微信运动的排行榜和定点推送复刻了一遍:100万次步数更新只要4秒,坑在别处
redis·后端·性能优化
文丑颜不良啊9 小时前
LeetCode876~900题目解析
java·leetcode
aloha_7899 小时前
Java 基础、集合、异常与 JUnit 5 速查
java·junit·sqlserver
知守观10 小时前
设计模式实战:从真实老项目中看标准模板方法与工厂的落地
java·spring·设计模式
独隅10 小时前
Claude API 实战教程:从入门到完整项目
android·java·数据库·claude·claude code
_孤傲_10 小时前
快速掌握 MySQL 语法
数据库·后端·mysql
Wang's Blog10 小时前
Java 项目实战: 交友项目 - 圈子功能实现:总结
java·开发语言·交友
SL_staff10 小时前
JVS私有化文档系统上线避坑指南:5大运维与业务协同断点及检测加固实践
java·开源·全栈