go语言ORM框架ent使用教程

ent是什么

ent是一个简单而又功能强大的Go语言实体框架,ent易于构建和维护应用程序与大数据模型。

简而言之,ent是一款便于操作的orm框架

installation

go get entgo.io/ent/cmd/ent

使用

创建schema

在连接ent之前,我们首先需要创建schema,创建schema的作用类似django创建model,规定数据表字段,定义表名等

cli创建model模板命令

ent init --target <target dirpath> <Model Name>

--target目的是指定创建模板路径, Model Name必须使用驼峰命名法

我们可以通过ent init --target spec/schema Class Student命令在spec/schema目录下创建两个模板,class.go和student.go

如下所示:

// spec/schema/class.go

package schema

import (
	"entgo.io/ent"
)

// Class holds the schema definition for the Class entity.
type Class struct {
	ent.Schema
}

// Fields of the Class.
func (Class) Fields() []ent.Field {
	return nil
}

// Edges of the Class.
func (Class) Edges() []ent.Edge {
	return nil
}
// spec/schema/student.go

package schema

import (
	"entgo.io/ent"
)

// Student holds the schema definition for the Student entity.
type Student struct {
	ent.Schema
}

// Fields of the Student.
func (Student) Fields() []ent.Field {
	return nil
}

// Edges of the Student.
func (Student) Edges() []ent.Edge {
	return nil
}

创建完整的数据结构

我们在生成的模板内,将表字段添加进去

// spec/schema/class.go

package schema

import (
	"entgo.io/ent"
	"entgo.io/ent/dialect/entsql"
	"entgo.io/ent/schema"
	"entgo.io/ent/schema/edge"
	"entgo.io/ent/schema/field"
)

// Class holds the schema definition for the Class entity.
type Class struct {
	ent.Schema
}

// Fields of the Class.
func (Class) Fields() []ent.Field {
	return []ent.Field{
		field.String("name").MaxLen(50).Comment("名称"),
		field.Int("level").Comment("级别"),
	}
}

// Edges of the Class.
func (Class) Edges() []ent.Edge {
	return []ent.Edge{
		edge.To("student", Student.Type),
	}
}

func (Class) Annotations() []schema.Annotation {
	return []schema.Annotation{
		entsql.Annotation{Table: "class"},
	}
}

// spec/schema/student.go

package schema

import (
	"entgo.io/ent"
	"entgo.io/ent/dialect/entsql"
	"entgo.io/ent/schema"
	"entgo.io/ent/schema/edge"
	"entgo.io/ent/schema/field"
)

// Student holds the schema definition for the Student entity.
type Student struct {
	ent.Schema
}

// Fields of the Student.
func (Student) Fields() []ent.Field {
	return []ent.Field{
		field.String("name").MaxLen(50).Comment("名称"),
		field.Bool("sex").Comment("性别"),
		field.Int("age").Comment("年龄"),
		field.Int("class_id").Comment("班级ID"),
	}
}

// Edges of the Student.
func (Student) Edges() []ent.Edge {
	return []ent.Edge{
		edge.From("class", Class.Type).
			Ref("student").
			Unique().
			Field("class_id").
			Required(),
	}
}

func (Student) Annotations() []schema.Annotation {
	return []schema.Annotation{
		entsql.Annotation{
			Table:       "student",
		},
	}
}

生成代码

基于schema的定义(字段,索引,边,配置)来生成对应的数据表操作代码

ent generate --target