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)

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

相关推荐
2301_79218588几秒前
基于软件工程的结构化设计实验
数据库·oracle·软件工程
小宇的天下7 分钟前
Allegro AXL (SKILL Extension) 手册核心内容结构化总结
数据库·oracle
CodeAmaz24 分钟前
Redis与数据库双写一致性详解
数据库·redis·缓存·数据一致性
Data_agent29 分钟前
京东商品价格历史信息API使用指南
java·大数据·前端·数据库·python
weixin_4454766829 分钟前
线上问题排查记录——MySQL 子查询报错 “Subquery returns more than 1 row” 问题总结
数据库·mysql
学习编程的Kitty33 分钟前
Redis(2)——事务
数据库·redis·缓存
最贪吃的虎37 分钟前
Spring Boot 自动装配(Auto-Configuration)深度实现原理全解析
java·运维·spring boot·后端·mysql
小波小波轩然大波38 分钟前
mysql技术
数据库·mysql
阿方索1 小时前
MySQL
数据库·mysql
蓝影铁哥1 小时前
浅谈国产数据库OceanBase
java·linux·数据库·oceanbase