Skip to content

03 · 数据层:BaseModel 与 128 张表 ​

配套文档:02 架构;本文结论全部基于反编译 hc-starter-mybatis 源码 + 本地 PG 实测

一、BaseModel 到底有什么(反编译精确版) ​

每个实体都 extends BaseModel(com.hc.mybatis.model.BaseModel,来自 hc-starter-mybatis)。反编译后它的全部字段只有 8 个:

java
public class BaseModel<T extends Model<?>> extends Model<T> {
    private Long id;                       // 主键
    private Integer deleted;               // 逻辑删除 0/1
    private Long createBy;                 // 创建人用户 id
    private String createName;             // 创建人用户名
    private LocalDateTime createTime;      // 创建时间
    private Long updateBy;                 // 修改人用户 id
    private String updateName;             // 修改人用户名
    private LocalDateTime updateTime;      // 修改时间
}

关键认知(容易搞错):

  1. BaseModel 没有 tenant_id 字段。多租户字段是每个实体自己声明的,例如 CustomerInfo 里:
    java
    @TableField("tenant_id")
    private String tenantId;
    
  2. BaseModel 继承的是 MyBatis-Plus 的 Model(ActiveRecord 风格),配合 @TableName/@TableField 注解做映射。
  3. createBy/createName/createTime/updateBy/updateName/updateTime 六个审计字段由拦截器/MetaObjectHandler 自动填充,业务代码不用手动 set。

对应到建表 DDL(resources/sql/init.sql),每张表都必须包含这些公共字段,这是全项目的铁律:

sql
create table xxx (
    id            bigint not null comment '主键id',
    tenant_id     varchar(64) not null comment '租户id',        -- 各实体自己声明
    ...业务字段...,
    create_by     bigint default null comment '创建人用户id',
    create_name   varchar(50) default null comment '创建人用户名',
    create_time   datetime default null comment '创建时间',
    update_by     bigint default null comment '更新人用户id',
    update_name   varchar(50) default null comment '修改人用户名',
    update_time   datetime default null comment '修改时间',
    deleted       tinyint(1) not null default 0 comment '是否已删除',
    primary key (id)
);

二、两条「隐形的数据库规则」 ​

2.1 多租户:tenant_id 自动追加 ​

TenantContextHolder(反编译)是一个 ThreadLocal<String>,提供 setTenantId/getTenantId/clear。请求进入时从登录上下文取出租户 id 放进去,MyBatis 租户拦截器在所有 SQL 上自动追加 tenant_id = ?,实现物理隔离。

java
public final class TenantContextHolder {
    private static final ThreadLocal<String> THREAD_LOCAL_TENANT;
    public static void setTenantId(String);
    public static String getTenantId();
    public static void clear();
}

例外:product 表是全局共享的(@InterceptorIgnore / ignoreTables 配置),不追加租户条件。

2.2 逻辑删除:deleted 自动过滤 ​

deleted 字段配了 MyBatis-Plus 的 @TableLogic:

  • 查询自动追加 deleted = 0;
  • removeById/removeByIds 实际是 UPDATE deleted = 1,数据不物理删除。

唯一的坑:手写 SQL(@Select 注解、Provider 里拼字符串)时,拦截器不一定能帮你加,要自己写 deleted = 0。看 CustomerInfoMapper:

java
@Select("SELECT COUNT(*) FROM customer_info WHERE customer_name = #{customerName} and deleted = 0")
int countByName(@Param("customerName") String customerName);

三、128 张表按业务域分类(本地 PG 实测) ​

本地库 hc_crm_center 实际有 128 张业务表 + 一批 migration_* 迁移表。按前缀分域如下:

业务域表前缀数量级核心表对应 Controller 前缀
客户customer_*~22customer_info(主表)、customer_product_follow、customer_follow_record、customer_protect_configuration/customerInfo 等
合同contract_*~15contract、contract_charge_standard*、contract_settlement_rule/contract
项目评估project_evaluation_*~17project_evaluation、project_evaluation_charge_standard*/projectEvaluation
招投标bidding_*~14bidding_project、bidding_opportunity、bidding_project_platform/biddingProject
渠道返佣channel_*~9channel_report、channel_rebate_rule、channel_settlement_account/channelReport
费用支付expense_payment_*~9expense_payment_apply、expense_payment_fund_task/expensePayment
试单trial_order_*2trial_order_application、trial_order_product/trialOrder
基础资料industry_dict region product position business_chain business_model settlement_rule brand_owner_relation~10industry_dict(行业字典)、region(地区)、product(全局产品)/industryDict /region /product
系统/基础设施sys_file import_record users tianyancha_company_info debezium_signal5sys_file(通用附件)、import_record(导入记录)/sysFile
迁移中间表migration_*~26migration_customer_mapping 等(旧系统迁移,非业务)无

验证命令:

bash
psql -h 127.0.0.1 -p 5432 -U admin -d hc_crm_center \
  -c "select table_name from information_schema.tables where table_schema='public' and table_name like 'customer_%' order by table_name;"

四、从表反推「主表 + 子表」的关联套路 ​

这是读 CRM 代码最实用的技能:一张主表对应多张子表,子表用 xxx_id 外键关联。以客户为例:

text
customer_info(客户主表)
├── customer_region            customer_id → 客户地区(一对多)
├── customer_business_info     customer_id → 工商信息(一对一,取最新一条)
├── customer_contact           customer_id → 联系人(一对多)
├── customer_product_follow    customer_id → 跟进产品(一对多)
├── customer_follow_record     customer_id → 跟进记录(一对多)
├── customer_invoice           customer_id → 开票信息(一对多)
└── customer_bank_info         customer_id → 银行信息(一对多)

对应的,CustomerInfoServiceImpl.saveCustomerInfo 就是「主表落库 + 逐个保存子表」,CustomerInfoProvider 就是「主表 JOIN 子表或 EXISTS 子查询」——这就是 04、05 要讲的内容。

五、下一步 ​

数据层骨架清楚了,接下来 04 拆解动态查询框架(列表怎么查),这是整个项目最精华、也是你最初问「列表/自定义字段」的核心答案。

Lucking