二丫讲梵 二丫讲梵
首页
  • 最佳实践
  • 迎刃而解
  • Nginx
  • Php
  • Zabbix
  • AWS
  • Prometheus
  • Grafana
  • CentOS
  • Systemd
  • Docker
  • Rancher
  • Ansible
  • Ldap
  • Gitlab
  • GitHub
  • Etcd
  • Consul
  • RabbitMQ
  • Kafka
  • MySql
  • MongoDB
  • OpenVPN
  • KVM
  • VMware
  • Other
  • ELK
  • K8S
  • LLM
  • Nexus
  • Jenkins
  • 随写编年
  • 家人物语
  • 追忆青春
  • 父亲的朋友圈
  • 电影音乐
  • 效率工具
  • 博客相关
  • Shell
  • 前端实践
  • Vue学习笔记
  • Golang学习笔记
  • Golang编程技巧
  • 学习周刊
  • Obsidian插件周刊
关于
友链
  • 本站索引

    • 分类
    • 标签
    • 归档
  • 本站页面

    • 导航
    • 打赏
  • 我的工具

    • 备忘录清单 (opens new window)
    • json2go (opens new window)
    • gopher (opens new window)
    • 微信MD编辑 (opens new window)
    • 国内镜像 (opens new window)
    • 出口IP查询 (opens new window)
    • 代码高亮工具 (opens new window)
  • 外站页面

    • 开往 (opens new window)
    • ldapdoc (opens new window)
    • HowToStartOpenSource (opens new window)
    • vdoing-template (opens new window)
GitHub (opens new window)

二丫讲梵

行者常至,为者常成
首页
  • 最佳实践
  • 迎刃而解
  • Nginx
  • Php
  • Zabbix
  • AWS
  • Prometheus
  • Grafana
  • CentOS
  • Systemd
  • Docker
  • Rancher
  • Ansible
  • Ldap
  • Gitlab
  • GitHub
  • Etcd
  • Consul
  • RabbitMQ
  • Kafka
  • MySql
  • MongoDB
  • OpenVPN
  • KVM
  • VMware
  • Other
  • ELK
  • K8S
  • LLM
  • Nexus
  • Jenkins
  • 随写编年
  • 家人物语
  • 追忆青春
  • 父亲的朋友圈
  • 电影音乐
  • 效率工具
  • 博客相关
  • Shell
  • 前端实践
  • Vue学习笔记
  • Golang学习笔记
  • Golang编程技巧
  • 学习周刊
  • Obsidian插件周刊
关于
友链
  • 本站索引

    • 分类
    • 标签
    • 归档
  • 本站页面

    • 导航
    • 打赏
  • 我的工具

    • 备忘录清单 (opens new window)
    • json2go (opens new window)
    • gopher (opens new window)
    • 微信MD编辑 (opens new window)
    • 国内镜像 (opens new window)
    • 出口IP查询 (opens new window)
    • 代码高亮工具 (opens new window)
  • 外站页面

    • 开往 (opens new window)
    • ldapdoc (opens new window)
    • HowToStartOpenSource (opens new window)
    • vdoing-template (opens new window)
GitHub (opens new window)
  • Shell编程

  • Go编程笔记

  • 前端编程笔记

  • Go学习笔记

    • 基础部分

    • web框架

    • orm框架

      • gorm框架入门
        • 1,gorm 介绍
        • 2,安装
        • 3,连接数据库
          • 1,连接 MySQL
          • 2,连接 PostgreSQL
          • 3,连接 Sqlite3
          • 4,连接 SQL Server
        • 4,GORM 基本示例
          • 1,Docker 快速创建 MySQL 实例
          • 2,创建数据库
          • 3,GORM 操作 MySQL
        • 5,GORM Model 定义
          • 1,gorm.Model
          • 2,模型定义示例
          • 3,结构体标记(tags)
          • 1,支持的结构体标记(Struct tags)
          • 2,关联相关标记(tags)
        • 6,主键、表名、列名的约定
          • 1,主键(Primary Key)
          • 2,表名(Table Name)
          • 3,列名(Column Name)
          • 4,时间戳跟踪
          • 1,CreatedAt
          • 2,UpdatedAt
          • 3,DeletedAt
      • gorm框架创建与查询
      • gorm框架更新与删除
  • Vue-21年学习笔记

  • Vue-22年重学笔记

  • 编程世界
  • Go学习笔记
  • orm框架
二丫讲梵
2021-07-10
目录

gorm框架入门

文章发布较早,内容可能过时,阅读注意甄别。

gorm 是一个使用 Go 语言编写的 ORM 框架。它文档齐全,对开发者友好,支持主流数据库。

# 1,gorm 介绍

Github GORM (opens new window)

中文官方网站 (opens new window)内含十分齐全的中文文档,有了它你甚至不需要再继续向下阅读本文。

# 2,安装

go get -u github.com/jinzhu/gorm
1

# 3,连接数据库

连接不同的数据库都需要导入对应数据的驱动程序,GORM已经贴心的为我们包装了一些驱动程序,只需要按如下方式导入需要的数据库驱动即可:

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"
1
2
3
4

# 1,连接 MySQL

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()
}
1
2
3
4
5
6
7
8
9

# 2,连接 PostgreSQL

基本代码同上,注意引入对应postgres驱动并正确指定gorm.Open()参数。

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()
}
1
2
3
4
5
6
7
8
9

# 3,连接 Sqlite3

基本代码同上,注意引入对应sqlite驱动并正确指定gorm.Open()参数。

import (
  "github.com/jinzhu/gorm"
  _ "github.com/jinzhu/gorm/dialects/sqlite"
)

func main() {
  db, err := gorm.Open("sqlite3", "/tmp/gorm.db")
  defer db.Close()
}
1
2
3
4
5
6
7
8
9

# 4,连接 SQL Server

基本代码同上,注意引入对应mssql驱动并正确指定gorm.Open()参数。

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()
}
1
2
3
4
5
6
7
8
9

# 4,GORM 基本示例

注意:

  1. 本文以 MySQL 数据库为例,讲解 GORM 各项功能的主要使用方法。
  2. 往下阅读本文前,你需要有一个能够成功连接上的 MySQL 数据库实例。

# 1,Docker 快速创建 MySQL 实例

很多同学如果不会安装 MySQL 或者懒得安装 MySQL,可以使用一下命令快速运行一个 MySQL8.0.19 实例,当然前提是你要有 docker 环境…

在本地的13306端口运行一个名为mysql8019,root 用户名密码为root1234的 MySQL 容器环境:

docker run --name mysql8019 -p 13306:3306 -e MYSQL_ROOT_PASSWORD=root1234 -d mysql:8.0.19
1

在另外启动一个MySQL Client连接上面的 MySQL 环境,密码为上一步指定的密码root1234:

docker run -it --network host --rm mysql mysql -h127.0.0.1 -P13306 --default-character-set=utf8mb4 -uroot -p
1

# 2,创建数据库

在使用 GORM 前手动创建数据库db1:

CREATE DATABASE db1;
1

# 3,GORM 操作 MySQL

使用 GORM 连接上面的db1进行创建、查询、更新、删除操作。

package main

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

type UserInfo struct {
	Id     uint
	Name   string
	Gender string
	Hobby  string
}

func main() {
	db, err := gorm.Open("mysql", "root:root1234@(127.0.0.1:13306)/db1?charset=utf8mb4&parseTime=True&loc=Local")
	if err != nil {
		panic(err)
	}
	defer db.Close()
	// 创建表,自动迁移(把结构体和数据表进行对应)
	db.AutoMigrate(&UserInfo{})

	// 创建数据行
	//u1 := UserInfo{1, "eryajf", "男", "篮球"}
	//db.Create(&u1)

	// 查询数据
	var u UserInfo
	db.First(&u) //查询表中第一条数据保存到u中
	fmt.Printf("u:%#v\n", u)

	// 更新数据
	db.Model(&u).Update("hobby", "双色球")

	// 删除数据
	db.Delete(&u)
}
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

# 5,GORM Model 定义

在使用 ORM 工具时,通常我们需要在代码中定义模型(Models)与数据库中的数据表进行映射,在 GORM 中模型(Models)通常是正常定义的结构体、基本的 go 类型或它们的指针。 同时也支持sql.Scanner及driver.Valuer接口(interfaces)。

# 1,gorm.Model

为了方便模型定义,GORM 内置了一个gorm.Model结构体。gorm.Model是一个包含了ID, CreatedAt, UpdatedAt, DeletedAt四个字段的 Golang 结构体。

// gorm.Model 定义
type Model struct {
  ID        uint `gorm:"primary_key"`
  CreatedAt time.Time
  UpdatedAt time.Time
  DeletedAt *time.Time
}
1
2
3
4
5
6
7

你可以将它嵌入到你自己的模型中:

// 将 `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

# 2,模型定义示例

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:"-"` // 忽略本字段
}
1
2
3
4
5
6
7
8
9
10
11
12

# 3,结构体标记(tags)

使用结构体声明模型时,标记(tags)是可选项。gorm 支持以下标记:

# 1,支持的结构体标记(Struct tags)

结构体标记(Tag) 描述
Column 指定列名
Type 指定列数据类型
Size 指定列大小, 默认值 255
PRIMARY_KEY 将列指定为主键
UNIQUE 将列指定为唯一
DEFAULT 指定列默认值
PRECISION 指定列精度
NOT NULL 将列指定为非 NULL
AUTO_INCREMENT 指定列是否为自增类型
INDEX 创建具有或不带名称的索引, 如果多个索引同名则创建复合索引
UNIQUE_INDEX 和 INDEX 类似,只不过创建的是唯一索引
EMBEDDED 将结构设置为嵌入
EMBEDDED_PREFIX 设置嵌入结构的前缀
- 忽略此字段

# 2,关联相关标记(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 是否自动完成预加载的相关操作

# 6,主键、表名、列名的约定

# 1,主键(Primary Key)

GORM 默认会使用名为 ID 的字段作为表的主键。

type User struct {
  ID   string // 名为`ID`的字段会默认作为表的主键
  Name string
}

// 使用`AnimalID`作为主键
type Animal struct {
  AnimalID int64 `gorm:"primary_key"`
  Name     string
  Age      int64
}
1
2
3
4
5
6
7
8
9
10
11

# 2,表名(Table Name)

表名默认就是结构体名称的复数,例如:

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)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

也可以通过Table()指定表名:

// 方法三:使用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';
1
2
3
4
5
6
7
8
9

GORM 还支持更改默认表名称规则:

gorm.DefaultTableNameHandler = func (db *gorm.DB, defaultTableName string) string  {
  return "prefix_" + defaultTableName;
}
1
2
3

# 3,列名(Column Name)

列名由字段名称进行下划线分割来生成

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`
}
1
2
3
4
5
6

可以使用结构体 tag 指定列名:

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`
}
1
2
3
4
5

# 4,时间戳跟踪

# 1,CreatedAt

如果模型有 CreatedAt字段,该字段的值将会是初次创建记录的时间。

db.Create(&user) // `CreatedAt`将会是当前时间

// 可以使用`Update`方法来改变`CreateAt`的值
db.Model(&user).Update("CreatedAt", time.Now())
1
2
3
4

# 2,UpdatedAt

如果模型有UpdatedAt字段,该字段的值将会是每次更新记录的时间。

db.Save(&user) // `UpdatedAt`将会是当前时间

db.Model(&user).Update("name", "jinzhu") // `UpdatedAt`将会是当前时间
1
2
3

# 3,DeletedAt

如果模型有DeletedAt字段,调用Delete删除该记录时,将会设置DeletedAt字段为当前时间,而不是直接将记录从数据库中删除。

CRUD 通常指数据库的增删改查操作,本文详细介绍了如何使用 GORM 实现创建、查询、更新和删除操作。

微信 支付宝
上次更新: 2024/06/13, 22:13:45
通过jwt基于token实现登陆认证
gorm框架创建与查询

← 通过jwt基于token实现登陆认证 gorm框架创建与查询→

最近更新
01
记录二五年五一之短暂回归家庭
05-09
02
学习周刊-总第210期-2025年第19周
05-09
03
学习周刊-总第209期-2025年第18周
05-03
更多文章>
Theme by Vdoing | Copyright © 2017-2025 | 点击查看十年之约 | 浙ICP备18057030号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式