gorm概述与快速入门

特性

  • 全功能 ORM
  • 关联 (Has One,Has Many,Belongs To,Many To Many,多态,单表继承)
  • Create,Save,Update,Delete,Find 中钩子方法
  • 支持 PreloadJoins 的预加载
  • 事务,嵌套事务,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…
  • 每个特性都经过了测试的重重考验
  • 开发者友好

安装

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

  

快速入门

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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package main
 
import (
    "fmt"
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
)
 
const (
    host   = "xxx"
    port   = 8000
    user   = "username"
    passwd = "xxx"
    db     = "topgoer_gorm"
    other  = "charset=utf8mb4&parseTime=True&loc=Local"
)
 
type Product struct {
    gorm.Model
    Code string
    Price uint
}
 
func MyPrint(p interface{}) {
    fmt.Printf("type: %T\tvalue: %v\n", p, p)
}
 
func main() {
    dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?%s", user, passwd, host, port, db, other)
    db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
    if err != nil {
        fmt.Println("conn mysql fail", err)
        return
    }
    sqlDb, _ := db.DB()
    defer sqlDb.Close()  // 关闭链接
 
    // 自动检查User结构是否发生变化,变化则进行迁移
    db.AutoMigrate(&Product{})
 
    // create
    //db.Create(&Product{Code: "D42", Price: 100})
    //db.Create(&Product{Code: "D43", Price: 200})
 
    // read
    var product Product
    db.First(&product, 1)  // 根据整型主键查找
    MyPrint(product)
    db.First(&product, "code = ?", "D43"// 查找code字段为D43的记录
    MyPrint(product)
 
    // update 更新单个字段
    db.Model(&product).Update("price", 300)  // 将product的price更新为300
    MyPrint(product)
 
    // updates 更新多个字段
    db.Model(&product).Updates(Product{Code: "F43", Price: 400})  // 仅更新非零值字段
    MyPrint(product)
    db.Model(&product).Updates(map[string]interface{}{
        "Code": "F44",
        "Price": 500,
    })
    MyPrint(product)
 
    // delete,  注意:此处必须是结构体指针,不能是结构体实例
    db.Delete(new(Product), 1)  // 删除product
 
}

  

参考链接:https://gorm.io/zh_CN/docs/index.html

posted @   专职  阅读(148)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示