ent is a simple, yet powerful entity framework for Go, that makes it easy to build and maintain applications with large data-models and sticks with the following principles:
https://entgo.io/zh/docs/getting-started/
- Easily model database schema as a graph structure.
- Define schema as a programmatic Go code.
- Static typing based on code generation.
- Database queries and graph traversals are easy to write.
- Simple to extend and customize using Go templates.
搭建环境
docker run --name mysql -d -p 3306:3306 -e MYSQL_ROOT_PASSWORD=1234 mysql:latest
使用 Navicat 连接测试
创建测试用的数据库和表
导出创建sql语句
CREATE TABLE `users` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR ( 255 ) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '',
`email` VARCHAR ( 255 ) COLLATE utf8mb4_general_ci NOT NULL DEFAULT '',
`password` VARCHAR ( 255 ) COLLATE utf8mb4_general_ci NOT NULL,
PRIMARY KEY ( `id` )
) ENGINE = INNODB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_general_ci;
创建golang项目
mkdir test-ent
go mod init test-ent
code .
go get ariga.io/entimport/cmd/entimport
生成 ent schema
go install entgo.io/ent/cmd/ent@latest
ent init
go run ariga.io/entimport/cmd/entimport -dsn "mysql://root:1234@tcp(127.0.0.1:3306)/test" -tables "users
生成后的 schema
// Code generated by entimport, DO NOT EDIT.
package schema
import (
"entgo.io/ent"
"entgo.io/ent/schema"
"entgo.io/ent/schema/field"
)
type User struct {
ent.Schema
}
func (User) Fields() []ent.Field {
return []ent.Field{field.Uint32("id"), field.String("name"), field.String("email"), field.String("password")}
}
func (User) Edges() []ent.Edge {
return nil
}
func (User) Annotations() []schema.Annotation {
return nil
}
执行生成
go generate ./ent
连接数据库
不要忘记哦~
go get "github.com/go-sql-driver/mysql"
package main
import (
"context"
"fmt"
"log"
"test-ent/ent"
_ "github.com/go-sql-driver/mysql"
)
func main() {
client, err := ent.Open("mysql", "root:1234@tcp(127.0.0.1:3306)/test?parseTime=True")
if err != nil {
log.Fatalf("failed opening connection to mysql: %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)
}
log.Println(CreateUser(context.Background(), client))
}
func CreateUser(ctx context.Context, client *ent.Client) (*ent.User, error) {
u, err := client.User.
Create().
SetEmail("[email protected]").
SetName("enjoy").
SetPassword("password").
Save(ctx)
if err != nil {
return nil, fmt.Errorf("failed creating user: %v", err)
}
log.Println("user was created: ", u)
return u, nil
}
go run .
2022/12/28 18:27:41 user was created: User(id=1, name=enjoy, [email protected], password=password)
2022/12/28 18:27:41 User(id=1, name=enjoy, [email protected], password=password) <nil>