在使用 Kratos 微服务框架 开发服务时,我们经常需要和数据库打交道。
相比手动写 SQL 建表,使用 GORM 的 AutoMigrate 自动建表功能 更加方便、优雅。
本文将以 教师(Teacher)表 为例,讲解如何在 Kratos 中完成 GORM 的自动建表流程。
需要提前下好gorm依赖,以及使用的数据库驱动(比如mysql)
go get gorm.io/gorm
go get gorm.io/driver/mysql
1、创建一个数据表模型
有两种方式:
1、在data/model下创建一个teacher.gen.go 文件 在这个文件中添加模型
2、在data/teacher.go中添加模型
这里以第一种方式为例子
const TableNameTeacher = "teacher"
// Teacher mapped from table <teacher>
type Teacher struct {
ID int32 `gorm:"column:id;primaryKey;autoIncrement:true;comment:主键" json:"id"` // 主键
Name string `gorm:"column:name;not null;comment:姓名" json:"name"` // 姓名
Age int8 `gorm:"column:age;not null;comment:年龄" json:"age"` // 年龄
CreatedAt time.Time `gorm:"column:created_at;not null;comment:创建时间" json:"created_at"` // 创建时间
UpdatedAt time.Time `gorm:"column:updated_at;not null;comment:更新时间" json:"updated_at"` // 更新时间
}
// TableName Teacher's table name
func (*Teacher) TableName() string {
return TableNameTeacher
}
其中 gorm .... 这一段是叫结构体标签,用于对结构体原字段的描述,告诉数据库这个表的字段定义。 需要注意的是不同的数据库它的结构体标签是不一样的,这里使用的是mysql。
💡 小提示:
大家在定义模型的结构体时,可以先写好字段名以及类型,后面的gorm ... 可以交给ai去生成。
2、在config下配置数据库信息
这里没什么好说的,大家把数据库信息填入config.yaml即可
data:
database:
driver: mysql
source: "" # 或者使用分开的配置
user: root
password: "123456"
host: 127.0.0.1
port: 3306
dbname: hhj```
3、在conf下配置数据库信息的类型
在conf.proto中填入配置类中的数据库字段类型
message Data {
Database database = 1;
message Database {
string driver = 1;
string source = 2;
string user = 3;
string password = 4;
string host = 5;
int32 port = 6;
string dbname = 7;
}
写好后执行命令,重新生成配置文件
make config
或
kratos proto client api/conf/conf.proto
4、在data下 完成NewDB方法
以下是data.go的代码
// ProviderSet is data providers.
var ProviderSet = wire.NewSet(NewData, NewDB, NewGreeterRepo, NewStudentRepo, NewUserRepo, NewTeacherRepo)
// Data .
type Data struct {
db *gorm.DB
log *log.Helper
}
// NewData .
func NewData(c *conf.Data, logger log.Logger, db *gorm.DB) (*Data, func(), error) {
cleanup := func() {
log.NewHelper(logger).Info("closing the data resources")
}
return &Data{
db: db,
}, cleanup, nil
}
// NewDB
func NewDB(c *conf.Data) *gorm.DB {
//表管理
models := []interface{}{
&model.Teacher{},
}
// 使用分开的字段构建连接字符串
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
c.Database.User,
c.Database.Password,
c.Database.Host,
c.Database.Port,
c.Database.Dbname,
)
// 打开数据库连接
db, err := gorm.Open(mysql.Open(dsn))
if err != nil {
panic("failed to connect database")
}
//automigrate 用于自动建表,使用models...是自动解析model下的模型
//如果是在teacher.go中定义的模型,可以使用&teacher替代models...
if err := db.AutoMigrate(models...); err != nil {
log.Debug("failed to migrate database")
panic(err)
}
return db
}
如果表已存在,GORM 会自动跳过创建,只会在必要时新增字段。
注意事项:
在conf中引入新配置后,需要在wire.go和main.go中声明一下
wire.go 中在wirApp中加入*conf.Data
// wireApp init kratos application.
func wireApp(*conf.Server, *conf.Data, log.Logger) (*kratos.App, func(), error) {
panic(wire.Build(server.ProviderSet, data.ProviderSet, biz.ProviderSet, service.ProviderSet, newApp))
}
main.go 中,wireApp方法中添加bc.Data
var bc conf.Bootstrap
if err := c.Scan(&bc); err != nil {
panic(err)
}
app, cleanup, err := wireApp(bc.Server, bc.Data, logger)
🎯 总结
通过以上步骤,我们实现了在 Kratos 框架中使用 GORM 自动建表 的完整流程:
1、定义模型结构体
2、配置数据库信息
3、在 conf.proto 中定义数据库配置
4、在 data 层中初始化 GORM
5、在项目启动时自动执行 AutoMigrate
这样一来,每次项目启动时都会自动检测并创建所需数据表,大大提高了开发效率。
✍️ 结语
如果你也在使用 Kratos + GORM,欢迎在评论区交流你的实践经验。
觉得文章有帮助的话,别忘了 点赞 + 收藏 + 关注,让更多人看到!
Kratos集成GORM自动建表
2861

被折叠的 条评论
为什么被折叠?



