GORM入门
官网
https://gorm.io/zh_CN/
安装
1 | go get -u github.com/jinzhu/gorm |
连接数据库
连接不同的数据库都需要导入对应数据的驱动程序,GORM
已经贴心的为我们包装了一些驱动程序,只需要按如下方式导入需要的数据库驱动即可:
1 2 3 4 | import _ "github.com/jinzhu/gorm/dialects/mysql" // import _ "github.com/jinzhu/gorm/dialects/postgres" // import _ "github.com/jinzhu/gorm/dialects/sqlite" // import _ "github.com/jinzhu/gorm/dialects/mssql" |
连接MySQL
1 2 3 4 5 6 7 8 9 | import ( "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" ) func main() { db, err := gorm.Open( "mysql" , "user:password@(localhost)/dbname?charset=utf8mb4&parseTime=True&loc=Local" ) defer db.Close() } |
连接PostgreSQL
基本代码同上,注意引入对应postgres
驱动并正确指定gorm.Open()
参数。
1 2 3 4 5 6 7 8 9 | import ( "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/postgres" ) func main() { db, err := gorm.Open( "postgres" , "host=myhost port=myport user=gorm dbname=gorm password=mypassword" ) defer db.Close() } |
连接Sqlite3
基本代码同上,注意引入对应sqlite
驱动并正确指定gorm.Open()
参数。
1 2 3 4 5 6 7 8 9 | import ( "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/sqlite" ) func main() { db, err := gorm.Open( "sqlite3" , "/tmp/gorm.db" ) defer db.Close() } |
连接SQL Server
基本代码同上,注意引入对应mssql
驱动并正确指定gorm.Open()
参数。
1 2 3 4 5 6 7 8 9 | import ( "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mssql" ) func main() { db, err := gorm.Open( "mssql" , "sqlserver://username:password@localhost:1433?database=dbname" ) defer db.Close() } |
GORM基本示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | package main import ( "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" ) type UserInfo struct { ID uint Name string Gender string Hobby string } func (UserInfo) TableName() string { return "UserInfo" } func main() { db, err := gorm.Open( "mysql" , "root:@(127.0.0.1:3306)/go_demo?charset=utf8mb4&parseTime=True&loc=Local" ) if err != nil { panic(err) } defer db.Close() db.AutoMigrate(&UserInfo{}) // 新增 u1 := UserInfo{1, "zys" , "man" , "篮球" } u2 := UserInfo{2, "zys1" , "man" , "足球" } db.Create(u1) db.Create(u2) // 查询 //var u = new(UserInfo) //db.First(u) //fmt.Println(*u) //fmt.Printf("%#v\n", u) // 更新 //db.Model(&u).Update("hobby","双色球") //db.First(u) //fmt.Println(u) // 删除 //db.Delete(&u) } |
GORM Model定义
在使用ORM工具时,通常我们需要在代码中定义模型(Models)与数据库中的数据表进行映射,在GORM中模型(Models)通常是正常定义的结构体、基本的go类型或它们的指针。 同时也支持sql.Scanner
及driver.Valuer
接口(interfaces)。
gorm.Model
为了方便模型定义,GORM内置了一个gorm.Model
结构体。gorm.Model
是一个包含了ID
, CreatedAt
, UpdatedAt
, DeletedAt
四个字段的Golang结构体。
1 2 3 4 5 6 7 | // gorm.Model 定义 type Model struct { ID uint `gorm: "primary_key" ` CreatedAt time.Time UpdatedAt time.Time DeletedAt *time.Time } |
你可以将它嵌入到你自己的模型中:
1 2 3 4 5 | // 将 `ID`, `CreatedAt`, `UpdatedAt`, `DeletedAt`字段注入到`User`模型中 type User struct { gorm.Model Name string } |
当然你也可以完全自己定义模型:
1 2 3 4 5 | // 不使用gorm.Model,自行定义模型 type User struct { ID int Name string } |
模型定义示例
1 2 3 4 5 6 7 8 9 10 11 12 | type User struct { gorm.Model Name string Age sql.NullInt64 Birthday *time.Time Email string `gorm: "type:varchar(100);unique_index" ` Role string `gorm: "size:255" ` // 设置字段大小为255 MemberNumber *string `gorm: "unique;not null" ` // 设置会员号(member number)唯一并且不为空 Num int `gorm: "AUTO_INCREMENT" ` // 设置 num 为自增类型 Address string `gorm: "index:addr" ` // 给address字段创建名为addr的索引 IgnoreMe int `gorm: "-" ` // 忽略本字段 } |
结构体标记(tags)
使用结构体声明模型时,标记(tags)是可选项。gorm支持以下标记:
支持的结构体标记(Struct tags)
结构体标记(Tag) | 描述 |
---|---|
Column | 指定列名 |
Type | 指定列数据类型 |
Size | 指定列大小, 默认值255 |
PRIMARY_KEY | 将列指定为主键 |
UNIQUE | 将列指定为唯一 |
DEFAULT | 指定列默认值 |
PRECISION | 指定列精度 |
NOT NULL | 将列指定为非 NULL |
AUTO_INCREMENT | 指定列是否为自增类型 |
INDEX | 创建具有或不带名称的索引, 如果多个索引同名则创建复合索引 |
UNIQUE_INDEX | 和 INDEX 类似,只不过创建的是唯一索引 |
EMBEDDED | 将结构设置为嵌入 |
EMBEDDED_PREFIX | 设置嵌入结构的前缀 |
- | 忽略此字段 |
关联相关标记(tags)
结构体标记(Tag) | 描述 |
---|---|
MANY2MANY | 指定连接表 |
FOREIGNKEY | 设置外键 |
ASSOCIATION_FOREIGNKEY | 设置关联外键 |
POLYMORPHIC | 指定多态类型 |
POLYMORPHIC_VALUE | 指定多态值 |
JOINTABLE_FOREIGNKEY | 指定连接表的外键 |
ASSOCIATION_JOINTABLE_FOREIGNKEY | 指定连接表的关联外键 |
SAVE_ASSOCIATIONS | 是否自动完成 save 的相关操作 |
ASSOCIATION_AUTOUPDATE | 是否自动完成 update 的相关操作 |
ASSOCIATION_AUTOCREATE | 是否自动完成 create 的相关操作 |
ASSOCIATION_SAVE_REFERENCE | 是否自动完成引用的 save 的相关操作 |
PRELOAD | 是否自动完成预加载的相关操作 |
主键、表名、列名的约定
主键(Primary Key)
GORM 默认会使用名为ID的字段作为表的主键。
1 2 3 4 5 6 7 8 9 10 11 | type User struct { ID string // 名为`ID`的字段会默认作为表的主键 Name string } // 使用`AnimalID`作为主键 type Animal struct { AnimalID int64 `gorm: "primary_key" ` Name string Age int64 } |
表名(Table Name)
表名默认就是结构体名称的复数,例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | type User struct {} // 默认表名是 `users` // 将 User 的表名设置为 `profiles` func (User) TableName() string { return "profiles" } func (u User) TableName() string { if u.Role == "admin" { return "admin_users" } else { return "users" } } // 禁用默认表名的复数形式,如果置为 true,则 `User` 的默认表名是 `user` db.SingularTable(true |
也可以通过Table()
指定表名:
1 2 3 4 5 6 7 8 9 | // 使用User结构体创建名为`deleted_users`的表 db.Table( "deleted_users" ).CreateTable(&User{}) var deleted_users []User db.Table( "deleted_users" ).Find(&deleted_users) //// SELECT * FROM deleted_users; db.Table( "deleted_users" ).Where( "name = ?" , "jinzhu" ).Delete() //// DELETE FROM deleted_users WHERE name = 'jinzhu'; |
GORM还支持更改默认表名称规则:
1 2 3 | gorm.DefaultTableNameHandler = func (db *gorm.DB, defaultTableName string) string { return "prefix_" + defaultTableName; } |
列名(Column Name)
列名由字段名称进行下划线分割来生成
1 2 3 4 5 6 | type User struct { ID uint // column name is `id` Name string // column name is `name` Birthday time.Time // column name is `birthday` CreatedAt time.Time // column name is `created_at` } |
可以使用结构体tag指定列名:
1 2 3 4 5 | type Animal struct { AnimalId int64 `gorm: "column:beast_id" ` // set column name to `beast_id` Birthday time.Time `gorm: "column:day_of_the_beast" ` // set column name to `day_of_the_beast` Age int64 `gorm: "column:age_of_the_beast" ` // set column name to `age_of_the_beast` } |
时间戳跟踪
CreatedAt
如果模型有 CreatedAt
字段,该字段的值将会是初次创建记录的时间。
1 2 3 4 | db.Create(&user) // `CreatedAt`将会是当前时间 // 可以使用`Update`方法来改变`CreateAt`的值 db.Model(&user).Update( "CreatedAt" , time.Now()) |
UpdatedAt
如果模型有UpdatedAt
字段,该字段的值将会是每次更新记录的时间
1 2 3 | db.Save(&user) // `UpdatedAt`将会是当前时间 db.Model(&user).Update( "name" , "jinzhu" ) // `UpdatedAt`将会是当前时间 |
DeletedAt
如果模型有DeletedAt
字段,调用Delete
删除该记录时,将会设置DeletedAt
字段为当前时间,而不是直接将记录从数据库中删除。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)