规范
ApiHug persistence 扩展使用手册
将 proto message 映射为数据库实体、DDL 与持久化元数据。
apihug/protobuf/domain/persistence.proto + annotations.protomessage(表)与 field(列)import "apihug/protobuf/domain/annotations.proto";
annotations.proto 会引入 persistence.proto。文档上不应再把它写成依赖 extend/common.proto。
message Category {
option (hope.persistence.table) = {
name: "CATEGORY";
description: "宠物分类";
wires: [IDENTIFIABLE];
};
}
string name = 1 [(hope.persistence.column) = {
name: "NAME";
description: "分类名称";
nullable: false;
length: 32;
unique: true;
type: VARCHAR;
}];
true / false不要再使用 TRUE / FALSE 这类旧写法。
nullable: false;
unique: true;
insertable: false;
updatable: false;
searchable: true;
sortable: true;
不要再使用旧的包装写法:
length: 32;
precision: 10;
scale: 2;
而不是:
length: {value: 32}
precision: {value: 10}
wires 负责通用字段Wire | 作用 |
|---|---|
IDENTIFIABLE | 主键字段 |
AUDITABLE | 创建/更新时间与创建/更新人 |
DELETABLE | 逻辑删除字段 |
TENANTABLE | 租户字段 |
VERSIONABLE | 乐观锁版本字段 |
ALL | 启用全部通用能力 |
NONE | 完全自定义 |
示例:
option (hope.persistence.table) = {
name: "PET";
description: "宠物";
wires: [IDENTIFIABLE, AUDITABLE, DELETABLE];
};
| 字段 | 类型 | 说明 |
|---|---|---|
name | string | 列名 |
description | string | 业务说明 |
nullable | bool | 是否允许 NULL |
unique | bool | 是否唯一 |
insertable | bool | 是否参与插入 |
updatable | bool | 是否参与更新 |
searchable | bool | 是否允许查询 |
sortable | bool | 是否允许排序 |
type | Column.Type | 显式 SQL 类型 |
length | uint32 | 字符串长度 |
precision | uint32 | DECIMAL 总位数 |
scale | uint32 | DECIMAL 小数位数 |
default_value | string | 默认值 |
transient | bool | 非持久化字段 |
常用 Column.Type 包括:
VARCHARCHARINTEGERBIGINTDOUBLEDECIMALDATETIMETIMESTAMPBOOLEANBLOBCLOBTIME_WITH_TIMEZONETIMESTAMP_WITH_TIMEZONEROWID如果你要表达时区时间或数据库特定行标识,应优先使用这些已经存在的枚举,而不是自己发明兼容写法。
int64 id = 1 [(hope.persistence.column) = {
name: "ID";
id: true;
nullable: false;
generated_value: {
strategy: UUID;
};
}];
常见策略:
AUTOTABLESEQUENCEIDENTITYUUIDcom.example.pet.enumeration.Size size = 4 [(hope.persistence.column) = {
name: "SIZE";
nullable: false;
enum_type: STRING;
type: VARCHAR;
length: 32;
}];
推荐:
STRINGCODE不推荐继续使用旧式位置型映射思路。
message Pet {
option (hope.persistence.table) = {
name: "PET";
description: "宠物信息表";
wires: [IDENTIFIABLE, AUDITABLE, DELETABLE];
};
string name = 1 [(hope.persistence.column) = {
name: "NAME";
description: "宠物名称";
nullable: false;
length: 32;
type: VARCHAR;
}];
string category = 2 [(hope.persistence.column) = {
name: "CATEGORY";
description: "宠物分类";
nullable: false;
length: 32;
type: VARCHAR;
}];
double weight = 3 [(hope.persistence.column) = {
name: "WEIGHT";
description: "宠物体重";
nullable: false;
type: DOUBLE;
}];
double price = 4 [(hope.persistence.column) = {
name: "PRICE";
description: "售价";
nullable: false;
type: DECIMAL;
precision: 10;
scale: 2;
}];
}
当实体需要列表视图、详情视图或数据库定制 SQL 时,再使用:
viewsliquibase这些能力是高级建模能力,不建议在基础实体阶段滥用。
wirestrue / false{value: ...} 包装DECIMAL + precision + scale