一、痛點(diǎn)分析:公共字段維護(hù)的三大困境
1.1 典型問題場景
// 訂單創(chuàng)建邏輯publicvoidcreateOrder(OrderDTO dto){ Order order = convertToEntity(dto); // 手動設(shè)置公共字段 order.setCreateTime(LocalDateTime.now()); order.setUpdateTime(LocalDateTime.now()); order.setCreateUser(getCurrentUser()); order.setUpdateUser(getCurrentUser()); orderMapper.insert(order);} // 訂單更新邏輯 publicvoidupdateOrder(OrderDTO dto){ Order order = convertToEntity(dto); // 重復(fù)設(shè)置邏輯 order.setUpdateTime(LocalDateTime.now()); order.setUpdateUser(getCurrentUser()); orderMapper.updateById(order);}
AI生成項(xiàng)目go運(yùn)行
痛點(diǎn)總結(jié):
- 代碼重復(fù)率高(每個Service方法都要設(shè)置)
- 維護(hù)成本高(字段變更需修改多處)
- 容易遺漏(特別是更新操作)
二、基礎(chǔ)方案:MyBatis-Plus自動填充
2.1 配置元對象處理器
@Slf4j@ComponentpublicclassAutoFillHandlerimplementsMetaObjectHandler{ // 插入時自動填充 @Override publicvoidinsertFill(MetaObject metaObject){ this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now()); this.strictInsertFill(metaObject, "createUser", String.class, getCurrentUser()); this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); this.strictUpdateFill(metaObject, "updateUser", String.class, getCurrentUser()); } // 更新時自動填充 @Override publicvoidupdateFill(MetaObject metaObject){ this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); this.strictUpdateFill(metaObject, "updateUser", String.class, getCurrentUser()); } // 獲取當(dāng)前用戶(從安全上下文) private String getCurrentUser(){ return Optional.ofNullable(SecurityContextHolder.getContext()) .map(SecurityContext::getAuthentication) .map(Authentication::getName) .orElse("system"); }}
AI生成項(xiàng)目go運(yùn)行