模型基类
基础实体
xModels 包提供与 GORM 深度集成的基础实体类型
模型基类
xModels 包提供与 GORM 深度集成的基础实体类型与分页模型,自动处理主键生成、时间戳管理和分页响应构建。
import xModels "github.com/bamboo-services/bamboo-base-go/major/models"BaseEntity
基础实体结构体,适用于不需要软删除的数据表。
type BaseEntity struct {
ID xSnowflake.SnowflakeID `json:"id" gorm:"type:bigint;primaryKey;comment:主键"`
CreatedAt time.Time `json:"-" gorm:"autoCreateTime:milli;not null;comment:创建时间"`
UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime:milli;not null;comment:更新时间"`
}字段说明
字段
类型
GORM 标签说明
| 字段 | JSON | GORM 标签 |
|---|---|---|
ID | "id" | type:bigint;primaryKey |
CreatedAt | "-" (不输出) | autoCreateTime:milli;not null |
UpdatedAt | "updated_at" | autoUpdateTime:milli;not null |
使用示例
定义实体
package entity
import (
xModels "github.com/bamboo-services/bamboo-base-go/major/models"
xSnowflake "github.com/bamboo-services/bamboo-base-go/common/snowflake"
)
type User struct {
xModels.BaseEntity // 继承基础实体
Username string `gorm:"type:varchar(64);uniqueIndex" json:"username"`
Email string `gorm:"type:varchar(128);uniqueIndex" json:"email"`
Password string `gorm:"type:varchar(256)" json:"-"`
}
// 实现 GeneProvider 接口(可选)
func (u *User) GetGene() xSnowflake.Gene {
return xSnowflake.GeneUser
}创建记录
user := &entity.User{
Username: "zhangsan",
Email: "zhangsan@example.com",
Password: hashedPassword,
}
// ID 会自动生成,CreatedAt 和 UpdatedAt 会自动设置
db.Create(user)
fmt.Println(user.ID) // 1234567890123456789更新记录
// UpdatedAt 会自动更新
db.Model(&user).Update("username", "lisi")查询记录
var user entity.User
// 按 ID 查询
db.First(&user, "id = ?", "1234567890123456789")
// 按条件查询
db.Where("username = ?", "zhangsan").First(&user)GORM 钩子
BeforeCreate
在插入数据前自动执行:
func (e *BaseEntity) BeforeCreate(tx *gorm.DB) error {
if e.ID.IsZero() {
// 尝试从实体获取基因类型
gene := xSnowflake.GeneDefault
if provider, ok := tx.Statement.Dest.(GeneProvider); ok {
gene = provider.GetGene()
}
e.ID = xSnowflake.GenerateID(gene)
}
now := time.Now()
e.CreatedAt = now
e.UpdatedAt = now
return nil
}功能:
- 如果 ID 为零值,自动生成雪花 ID
- 检查实体是否实现
GeneProvider接口 - 实现了接口则使用自定义基因,否则使用默认基因
- 设置
CreatedAt和UpdatedAt为当前时间
BeforeUpdate
在更新数据前自动执行:
func (e *BaseEntity) BeforeUpdate(tx *gorm.DB) error {
e.UpdatedAt = time.Now()
return nil
}功能:
- 自动更新
UpdatedAt时间戳
数据库表结构
使用 BaseEntity 的实体会生成如下表结构:
CREATE TABLE users (
id BIGINT PRIMARY KEY,
created_at TIMESTAMP(3) NOT NULL,
updated_at TIMESTAMP(3) NOT NULL,
username VARCHAR(64) UNIQUE,
email VARCHAR(128) UNIQUE,
password VARCHAR(256)
);JSON 序列化
user := entity.User{
Username: "zhangsan",
Email: "zhangsan@example.com",
}
db.Create(&user)
data, _ := json.Marshal(user)输出:
{
"id": "1234567890123456789",
"updated_at": "2024-01-15T10:30:00.123Z",
"username": "zhangsan",
"email": "zhangsan@example.com"
}注意:
ID序列化为字符串(避免 JavaScript 精度丢失)CreatedAt不输出(json:"-")Password不输出(json:"-")