Goweb---Gorm操作数据库(二)

Gorm允许用户自己自定义钩子操作,使用这些钩子操作,可以在增删改查操作前进行相关的操作和检验,它会在创建、更新、查询、删除时自动被调用。如果任何回调返回错误,GORM 将停止后续的操作并回滚事务。

自定义钩子函数
go 复制代码
package main

import (
	"fmt"

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

type User struct {
	ID       int    `gorm:"column:id"`
	Name     string `gorm:"column:name"`
	Age      int    `gorm:"column:age"`
	Birthday string `gorm:"column:birthday"`
}

func (u *User) BeforeCreate(tx *gorm.DB) error {
	
	fmt.Println("BeforeCreate user : ", u.Name)
	return nil
}
func main() {

	dsn := "root:828924@tcp(127.0.0.1:3306)/user?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		fmt.Println("连接数据库失败:", err)
	}

	db.AutoMigrate(&User{})

	user := User{
		Name:     "张三",
		Age:      20,
		Birthday: "2000-01-01",
	}
	db.Create(&user)
}

func (u *User) BeforeCreate(tx *gorm.DB) error {

fmt.Println("BeforeCreate user : ", u.Name)

return nil

}

这是自定义的钩子函数,在用户执行db.Create(&user)前会执行BeforeCreate函数

其他相关操作都可以类推或者看相关文档

下面是Gorm的官方文档:
https://gorm.io/zh_CN/docs/create.html

跳过钩子函数:

可以通过使用SkipHooks会话模式跳过钩子函数

具体操作:

将db.Create(&user) 改为 db.Session(&gorm.Session{SkipHooks: true}).Create(&user)

在操作前将不会调用钩子函数。

相关推荐
Snk0xHeart17 分钟前
极客大挑战 2019 EasySQL 1(万能账号密码,SQL注入,HackBar)
数据库·sql·网络安全
····懂···1 小时前
数据库OCP专业认证培训
数据库·oracle·ocp
学习中的码虫1 小时前
数据库-MySQL
数据库
天天摸鱼的java工程师2 小时前
高考放榜夜,系统别崩!聊聊查分系统怎么设计,三张表足以?
java·后端·mysql
Karry的巡洋舰2 小时前
【数据库】安全性
数据库·oracle
软件测试小仙女2 小时前
鸿蒙APP测试实战:从HDC命令到专项测试
大数据·软件测试·数据库·人工智能·测试工具·华为·harmonyos
exe4522 小时前
jdbc查询mysql数据库时,出现id顺序错误的情况
数据库·mysql
John Song2 小时前
macOS 上使用 Homebrew 安装redis-cli
数据库·redis·macos
数据知道3 小时前
Mac电脑上本地安装 redis并配置开启自启完整流程
数据库·redis·macos
Lonely丶墨轩3 小时前
Redis 缓存策略:借助缓存优化数据库性能并保障数据一致性
数据库·redis·缓存