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 前/后的勾子
  • 基于 PreloadJoins 的预加载
  • 事务、嵌套事务、保存点、回滚至保存点
  • Context、Prepared Statment 模式、DryRun 模式
  • 批量插入、FindInBatches、查询至 Map
  • SQL Builder, Upsert, Locking, Optimizer/Index/Comment Hints
  • 复合主键
  • 自动迁移
  • 自定义 Logger
  • Extendable, flexible plugin API: Database Resolver (Read/Write Splitting) / Prometheus…
  • 所有特性都通过了测试
  • 开发者友好

安装

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

快速入门

  1. package main
  2. import (
  3. "gorm.io/gorm"
  4. "gorm.io/driver/sqlite"
  5. )
  6. type Product struct {
  7. gorm.Model
  8. Code string
  9. Price uint
  10. }
  11. func main() {
  12. db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
  13. if err != nil {
  14. panic("failed to connect database")
  15. }
  16. // Migrate the schema
  17. db.AutoMigrate(&Product{})
  18. // Create
  19. db.Create(&Product{Code: "D42", Price: 100})
  20. // Read
  21. var product Product
  22. db.First(&product, 1) // find product with integer primary key
  23. db.First(&product, "code = ?", "D42") // find product with code D42
  24. // Update - update product's price to 200
  25. db.Model(&product).Update("Price", 200)
  26. // Update - update multiple fields
  27. db.Model(&product).Updates(Product{Price: 200, Code: "F42"}) // non-zero fields
  28. db.Model(&product).Updates(map[string]interface{}{"Price": 200, "Code": "F42"})
  29. // Delete - delete product
  30. db.Delete(&product, 1)
  31. }