The fantastic ORM library for Golang aims to be developer friendly.
特性
- 全功能 ORM
- 关联 (Has One,Has Many,Belongs To,Many To Many,多态,单表继承)
- Create,Save,Update,Delete,Find 中钩子方法
- 支持
Preload
、Joins
的预加载
- 事务,嵌套事务,Save Point,Rollback To 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
|
快速入门
package main
import ( "gorm.io/gorm" "gorm.io/driver/sqlite" )
type Product struct { gorm.Model Code string Price uint }
func main() { db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) if err != nil { panic("failed to connect database") }
db.AutoMigrate(&Product{})
db.Create(&Product{Code: "D42", Price: 100})
var product Product db.First(&product, 1) db.First(&product, "code = ?", "D42")
db.Model(&product).Update("Price", 200) db.Model(&product).Updates(Product{Price: 200, Code: "F42"}) db.Model(&product).Updates(map[string]interface{}{"Price": 200, "Code": "F42"})
db.Delete(&product, 1) }
|