[GORM初体验 | 青训营笔记]

66 阅读3分钟

概述

The fantastic ORM library for Golang aims to be developer friendly.

一个致力于开发者友好、极好的Golang ORM类库。

特性

全功能 ORM 关联 (Has One,Has Many,Belongs To,Many To Many,多态,单表继承) Create,Save,Update,Delete,Find 中钩子方法 支持 Preload、Joins 的预加载 事务,嵌套事务,Save Point,回滚到 Saved Point Context、预编译模式、DryRun 模式 批量插入,FindInBatches,Find/Create with Map,使用 SQL 表达式、Context Valuer 进行 CRUD SQL 构建器,Upsert,数据库锁,Optimizer/Index/Comment Hint,命名参数,子查询 复合主键,索引,约束 Auto Migration 自定义 Logger 灵活的可扩展插件 API:Database Resolver(多数据库,读写分离)、Prometheus… 每个特性都经过了测试的重重考验 开发者友好

安装

go get -u gorm.io/gorm go get -u gorm.io/driver/sqlite

连接到数据库

GORM 官方支持的数据库类型有: MySQL, PostgreSQL, SQlite, SQL Server。

有些数据库可能兼容 mysqlpostgres 的方言,在这种情况下,你可以直接使用这些数据库的方言。

数据库配置

import (
  "gorm.io/driver/mysql"
  "gorm.io/gorm"
)

func main() {
  // 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
  dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
  db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
}

注意:想要正确的处理 time.Time ,您需要带上 parseTime 参数, (更多参数) 要支持完整的 UTF-8 编码,您需要将 charset=utf8 更改为 charset=utf8mb4 

还有一个配置:gorm.Config

// Config GORM config
type Config struct {
	// GORM perform single create, update, delete operations in transactions by default to ensure database data integrity
	// 是否跳过默认的事务
	SkipDefaultTransaction bool
	// 命名策略:表、列
	NamingStrategy schema.Namer
	// FullSaveAssociations full save associations
	FullSaveAssociations bool
	// 日志配置
	Logger logger.Interface
	// NowFunc the function to be used when creating a new timestamp
	NowFunc func() time.Time
	// 是否支持DryRun模式,只生成SQL,不执行
	DryRun bool
	// PrepareStmt executes the given query in cached statement
	PrepareStmt bool
	// DisableAutomaticPing
	DisableAutomaticPing bool
	// 迁移时禁用外键限制
	DisableForeignKeyConstraintWhenMigrating bool
	// 禁用嵌套事务
	DisableNestedTransaction bool
	// 是否允许全局修改(update语句不带任何条件),默认false
	AllowGlobalUpdate bool
	// QueryFields executes the SQL query with all fields of the table
	QueryFields bool
	// 默认批量创建的大小
	CreateBatchSize int

	// ClauseBuilders clause builder
	ClauseBuilders map[string]clause.ClauseBuilder
	// 使用的连接池配置
	ConnPool ConnPool
	// Dialector database dialector
	Dialector
	// 注册插件
	Plugins map[string]Plugin

	callbacks  *callbacks
	cacheStore *sync.Map
}

自定义驱动

GORM 允许通过 DriverName 选项自定义 MySQL 驱动(不使用默认的驱动),例如:

import (
  _ "example.com/my_mysql_driver"
  "gorm.io/gorm"
)

db, err := gorm.Open(mysql.New(mysql.Config{
  DriverName: "my_mysql_driver",
  DSN: "gorm:gorm@tcp(localhost:9910)/gorm?charset=utf8&parseTime=True&loc=Local", // Data Source Name,参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name
}), &gorm.Config{})

Gorm方法分类 GORM 允许进行链式操作,所以您可以像这样写代码:

db.Where("name = ?", "jinzhu").Where("age = ?", 18).First(&user) 1 GORM 中有三种类型的方法: 链式方法、Finisher 方法、新建会话方法

链式方法 链式方法是将 Clauses 修改或添加到当前 Statement 的方法,例如:

Where, Select, Omit, Joins, Scopes, Preload, Raw…

注意:如果使用Raw方法,即使用原生SQL的方式,便不能与其他的链式方法组合使用

Finisher Method Finishers 是会立即执行注册回调的方法,然后生成并执行 SQL,也称作立即执行方法,比如这些方法:

Create, First, Find, Take, Save, Update, Delete, Scan, Row, Rows…

新建会话模式 在初始化了 *gorm.DB 或 新建会话方法 后, 调用下面的方法会创建一个新的 Statement 实例而不是使用当前的

GROM 定义了 Session、WithContext、Debug 方法做为 `新建会话方法

这种模式可以避免Statement复用,可以用在需要考虑线程安全的场景。

这篇文章对# GORM有了一个初步认识