|
| 1 | +--- |
| 2 | +title: Gorm框架基本使用(四) |
| 3 | +date: 2025-03-28 05:41:38 |
| 4 | +updated: 2025-03-28 05:41:38 |
| 5 | +tags: |
| 6 | + - GO |
| 7 | +comments: false |
| 8 | +categories: GO |
| 9 | +thumbnail: https://images.unsplash.com/photo-1682687220499-d9c06b872eee?crop=entropy&cs=srgb&fm=jpg&ixid=M3w2NDU1OTF8MHwxfHJhbmRvbXx8fHx8fHx8fDE3NDMxNTQ4OTh8&ixlib=rb-4.0.3&q=85&w=1920&h=1080 |
| 10 | +published: true |
| 11 | +--- |
| 12 | +# 1. 下载 Gorm 依赖 |
| 13 | + |
| 14 | +## 1.1 gorm框架 |
| 15 | + |
| 16 | +> go get -u gorm.io/gorm |
| 17 | +
|
| 18 | +## 1.2 mysql驱动依赖 |
| 19 | + |
| 20 | +> go get -u gorm.io/driver/mysql |
| 21 | +
|
| 22 | +注意如果下载不了依赖:**go env -w GOPROXY=https://goproxy.cn,direct** 修改依赖代理网站 |
| 23 | + |
| 24 | +# 2. 快速开始 |
| 25 | + |
| 26 | +```go |
| 27 | +type Author struct { |
| 28 | + Email string |
| 29 | +} |
| 30 | +//指定当前实例的表名称,默认使用实例结构的 蛇型作为表名 |
| 31 | +func (u Userinfo) TableName() string { |
| 32 | + return "user_info" |
| 33 | +} |
| 34 | + |
| 35 | +type Userinfo struct { |
| 36 | + gorm.Model //使用 gorm.Model提供的实体,这里会将字段自动展开,封装了通用字段,例如id |
| 37 | + Author `gorm:"embeded"` //可以对正常的内嵌对象通过 embeded 标签嵌入 embeddedPrefix:author_ 增加前缀 |
| 38 | + Name string |
| 39 | + Gender string |
| 40 | + Hobby string |
| 41 | +} |
| 42 | + |
| 43 | +func main() { |
| 44 | + //创建连接获取 db对象 |
| 45 | + dsn := "root:root@tcp(localhost:3306)/db1?charset=utf8mb4&parseTime=True&loc=Local" |
| 46 | + db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) |
| 47 | + if err != nil { |
| 48 | + panic(err) |
| 49 | + } |
| 50 | + u1 := Userinfo{Name: "张四", Gender: "男", Hobby: "学习"} |
| 51 | + //如果没有表,会自动创建,如果存在表,就会执行插入数据 |
| 52 | + db.Create(&u1) |
| 53 | + //打印返回的ID |
| 54 | + fmt.Println(u1.ID) |
| 55 | + |
| 56 | +} |
| 57 | +``` |
| 58 | + |
| 59 | +# 3. 创建 |
| 60 | + |
| 61 | +## 3.1 实体 |
| 62 | + |
| 63 | +```go |
| 64 | +type Author struct { |
| 65 | + Email string |
| 66 | +} |
| 67 | + |
| 68 | +type Userinfo struct { |
| 69 | + gorm.Model //使用 gorm.Model提供的实体,这里会将字段自动展开 |
| 70 | + Author `gorm:"embeded"` //可以对正常的内嵌对象通过 embeded 标签嵌入 embeddedPrefix:author_ 增加前缀 |
| 71 | + Name string |
| 72 | + Gender string |
| 73 | + Hobby string |
| 74 | +} |
| 75 | +``` |
| 76 | + |
| 77 | + |
| 78 | + |
| 79 | +## 3.1 插入指定字段 |
| 80 | + |
| 81 | +```go |
| 82 | +func CreateAndUpdate(db *gorm.DB) { |
| 83 | + u1 := Userinfo{Name: "张四", Gender: "男", Hobby: "学习", Author: Author{Email: "[email protected]"}} |
| 84 | + //根据给出的字段插入数据 |
| 85 | + result := db.Select("Name", "Email", "Hobby").Create(&u1) |
| 86 | + fmt.Printf("ID:%d, Error:%v, 插入记录行数:%d \n", u1.ID, result.Error, result.RowsAffected) |
| 87 | + // INSERT INTO `user_info` (`name`,`gender`,`email`) VALUES ("jinzhu", 18, "[email protected]") |
| 88 | +} |
| 89 | +``` |
| 90 | + |
| 91 | +## 3.2 忽略字段 |
| 92 | + |
| 93 | +```go |
| 94 | +func CreateAndOmit(db *gorm.DB) { |
| 95 | + u1 := Userinfo{Name: "张四", Gender: "男", Hobby: "学习", Author: Author{Email: "[email protected]"}} |
| 96 | + //忽略指定的字段 |
| 97 | + result := db.Omit("Name", "Hobby").Create(&u1) |
| 98 | + fmt.Printf("ID:%d, Error:%v, 插入记录行数:%d \n", u1.ID, result.Error, result.RowsAffected) |
| 99 | +} |
| 100 | +``` |
| 101 | + |
| 102 | +## 3.3 批量插入 |
| 103 | + |
| 104 | +```go |
| 105 | +//也可以指定每个会话的批次大小:db := db.Session(&gorm.Session{CreateBatchSize: 1000}) |
| 106 | +//指定所有全局的大小:db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{ CreateBatchSize:1000,}) |
| 107 | + |
| 108 | +func batchInsert(db *gorm.DB) { |
| 109 | + users := []Userinfo{ |
| 110 | + {Name: "李四"}, |
| 111 | + {Name: "张三"}, |
| 112 | + } |
| 113 | + //指定每批的大小 |
| 114 | + db.CreateInBatches(users, 100) |
| 115 | + |
| 116 | + db.Create(users) |
| 117 | + for _, i := range users { |
| 118 | + fmt.Println("id:", i.ID) |
| 119 | + } |
| 120 | +} |
| 121 | +``` |
| 122 | + |
| 123 | +## 3.4 创建钩子 |
| 124 | + |
| 125 | +GORM允许用户自定义钩子: |
| 126 | + |
| 127 | +- BeforeSave:在保存之间 |
| 128 | +- BeforeCreate:创建之前 |
| 129 | +- AfterSave:保存之后 |
| 130 | +- AfterCreate:创建之后 |
| 131 | + |
0 commit comments