Appearance
05 · 表单入库:增删改查的完整链路
配套文档:04 动态查询框架;本文以
CustomerInfo(复杂样板)为主线,Region(最简样板)对照
一、先看数据是怎么「流」的
前端提交的 JSON 到数据库,中间经过 4 层对象,靠 Converter 和 ObjectUtils.copyProperties 转换:
text
前端 JSON
│ @RequestBody + @Valid(校验注解生效)
▼
Form(CustomerInfoAddForm) api 模块,入参 + 校验
│ CustomerInfoConverter.convertAddFormToDto(form)
▼
DTO(CustomerInfoDto) service 模块,内部编排(含子表 List)
│ ObjectUtils.copyProperties(dto, Entity.class)
▼
Entity(CustomerInfo) 继承 BaseModel,@TableName 映射
│ MyBatis-Plus save/updateById(租户/审计字段自动填)
▼
PostgreSQL
查询方向反过来:Entity → Converter.convertEntityToVo → VO → 返回。
二、参数校验:两个层次
2.1 Form 层:注解校验(@Valid 触发)
CustomerInfoController 方法签名 @Valid @RequestBody CustomerInfoAddForm,CustomerInfoAddForm 里:
java
@NotBlank(message = "客户名称不能为空")
private String customerName;
@NotNull(message = "是否海外客户不能为空")
private OverseasEnum isOverseas;
// 跨字段校验:非海外客户必须有税号
@AssertTrue(message = "*如果非海外客户,纳税人识别号/企业标识ID不能为空")
@JsonIgnore
public boolean isCustomerLicenseValid() {
if (isOverseas == OverseasEnum.YES) return true;
return customerLicense != null && !customerLicense.trim().isEmpty();
}
@AssertTrue放在 getter 方法上,能做跨字段校验(一个字段依赖另一个字段),这是单个@NotBlank做不到的。
2.2 Service 层:业务校验(抛 BusinessException)
注解只能拦格式问题,业务规则在 Service 里拦:
java
if (this.isCustomerNameExist(customerName)) {
throw new BusinessException("系统中已有客户“" + customerName + "”。...");
}
checkCustomerLicense(customerInfoDto); // 税号必填
三、新增(save):主表 + 子表联动,全程一个事务
saveCustomerInfo 标注 @Transactional(rollbackFor = Exception.class),完整流程:
- 查重:
isCustomerNameExist命中即抛异常; - 补派生字段:
UserContext.getOpenId()取当前用户 → 查主部门 → 设为creatorDepartmentId;按「参保人数 + 需求人数」算客户等级CustomerLevelEnum.resolve(...);取行业最后一级存industryId; - 主表落库:
this.save(customerInfo)(BaseModel 自动填创建人/时间/租户); - 写变更日志:
customerInfoChangeLogService.recordCreate(...)(每个操作都留痕); - 逐个保存子表:
- 地区
customer_region(遍历 regions 列表) - 工商信息
customer_business_info - 跟进产品+联系人
customer_product_follow - 跟进记录
customer_follow_record(还要回填customerProductFollowId、算截止时间applyDeadlineRule) - 开票
customer_invoice、银行customer_bank_info - 客户-商机关联
biddingOpportunityService.joinCustomer(...)
- 地区
关键点:每一步 save 之后都跟着一条 recordCreate 变更日志,这是项目的数据审计铁律。
四、编辑(edit):增量对比,不是全删重插
editCustomerInfo 也是 @Transactional,最值得学的是地区子表的增量更新(三份清单):
text
1. 查出库中已有地区 deleteCustomerRegions
2. 遍历新提交的地区,能匹配上就加入 keepRegionIds(保留,不删)
3. deleteRegionIds = 库中已有 - 保留 → recordDelete + remove
4. 剩下没匹配上的新地区 → recordCreate + saveBatch
工商信息则是「存在则 updateById、不存在则 save」的 upsert 逻辑。这种「对比旧数据、算出增/改/删三份」的写法,是处理一对多子表编辑的标准套路,务必掌握。
五、删除(delete):逻辑删除 + 业务卡点
java
@Transactional
public boolean deleteCustomerInfoById(Long id) {
CustomerInfo customerInfo = this.getById(id);
ParamChecker.notEmpty(customerInfo, "客户不存在");
Long followProductCount = customerProductFollowService.countAllFollowProductByCustomerId(id);
ParamChecker.expectFalse(followProductCount != null && followProductCount > 0, "客户存在跟进产品,禁止删除");
customerInfoChangeLogService.recordDelete(id, customerInfo, ModelLogChangeInfoTypeEnum.CUSTOMER_ENTITY);
return this.removeById(id); // 逻辑删除:UPDATE deleted=1
}
三个要点:
- 删除前先做业务卡点(有跟进产品就不让删)——
ParamChecker.expectFalse; - 删除也留痕——
recordDelete; removeById是逻辑删除(BaseModel.deleted配了@TableLogic),数据还在,只是查不到。
批量删除 deleteCustomerInfoByIds 只是循环调单个删除(每个都走完整校验+日志)。
六、读详情(findById):富 VO 组装
getCustomerInfoById 返回的不是裸实体,而是一个「拼装好所有中文名和关联信息」的富 VO:
java
CustomerInfo customerInfo = this.baseMapper.selectById(id); // 1. 主表
CustomerInfoVo vo = CustomerInfoConverter.convertEntityToVo(customerInfo); // 2. 实体转 VO
vo.setEditable(checkEditCustomerPermission(id)); // 3. 权限:能不能编辑
vo.setNatureTypeName(dictItem.getItemLabel()); // 4. 字典码 → 中文名
vo.setIndustryName(industryDictService.getIndustryNameById(...)); // 5. 行业名 + 祖先路径
// ... 继续补地区、品牌名、首位签约人、客户等级等
详情接口 = 主表查询 + 一堆 Service 补充查询拼装成富 VO。这是 06 要专门展开的。
七、最简样板对照:Region
RegionController 是最简 CRUD 模板,五个接口直接调 MyBatis-Plus 的通用方法:
java
@PostMapping("/save") saveOrUpdate(convertFormToEntity(region)) // 有 id 就改,无 id 就增
@PostMapping("/edit") saveOrUpdate(...)
@PostMapping("/del/batch") removeByIds(ids) // 逻辑删除
@PostMapping("/findById") getById(id) // 详情
@PostMapping("/query/page") queryPage(model) // 列表(走 Provider)
结论:MyBatis-Plus 的 BaseMapper 免费提供了单表增删改查;复杂业务(查重、联动、日志、增量对比)才需要像 CustomerInfoServiceImpl 那样手写。
八、下一步
增删改查链路清楚了。06 讲详情接口的富 VO 组装细节 + 各种自定义接口(下拉、导出、数据范围查询)的写法。
