ent 是 facebook 开源的golang orm 框架,简单强大,以下是一个简单使用
环境准备
- 安装ent 工具
go get github.com/facebookincubator/ent/cmd/entc
- 准备mysql 环境
使用docker-compose 运行
docker-compose 文件
version: "3"
services:
mysql:
image: mysql:5.7.16
ports:
- 3306:3306
command: --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
environment:
MYSQL_ROOT_PASSWORD: dalongrong
MYSQL_DATABASE: gogs
MYSQL_USER: gogs
MYSQL_PASSWORD: dalongrong
TZ: Asia/Shanghai
启动
docker-compose up -d
- 初始化一个golang 项目
go mod init github.com/rongfengliang/ent-demo
使用
- 初始化schema
entc init User
效果:
├── docker-compose.yaml
└── ent
└── schema
└── user.go
golang 代码内容:
package schema
import "github.com/facebookincubator/ent"
// User holds the schema definition for the User entity.
type User struct {
ent.Schema
}
// Fields of the User.
func (User) Fields() []ent.Field {
return nil
}
// Edges of the User.
func (User) Edges() []ent.Edge {
return nil
}
- 添加字段
package schema
import (
"github.com/facebookincubator/ent"
"github.com/facebookincubator/ent/schema/field"
)
// User holds the schema definition for the User entity.
type User struct {
ent.Schema
}
// Fields of the User.
func (User) Fields() []ent.Field {
return []ent.Field{
field.Int("age").
Positive(),
field.String("name").
Default("unknown"),
}
}
// Edges of the User.
func (User) Edges() []ent.Edge {
return nil
}
- 生成代码
entc generate ./ent/schema
效果:
- 编写入口
main.go
package main
import (
"log"
"github.com/rongfengliang/ent-demo/ent"
"context"
_ "github.com/go-sql-driver/mysql"
)
func main() {
client, err := ent.Open("mysql", "root:dalongrong@tcp(127.0.0.1)/gogs")
if err != nil {
log.Fatalf("failed opening connection to sqlite: %v", err)
}
defer client.Close()
// run the auto migration tool.
if err := client.Schema.Create(context.Background()); err != nil {
log.Fatalf("failed creating schema resources: %v", err)
}
}
- 运行
说明:以上是一个schema 的处理
go run main.go
- 数据库效果
说明
以上是一个简单的运行 ,后边会有一些其他的使用说明
参考资料
https://entgo.io/docs/getting-started/
https://github.com/facebookincubator/ent
https://github.com/rongfengliang/ent-demo