xorm框架中,可以通过在结构体字段上添加 beforeupdate 标签来注册钩子函数。当调用 update 方法时,xorm会自动执行该函数,常用于在更新前修改数据(如更新时间戳)或进行业务校验。

如何定义并触发 BeforeUpdate 钩子
在结构体字段上使用 xorm:"before(update)" 标签即可绑定一个无参、无返回值的函数。执行 Update 时,XORM会先调用此函数,再组装SQL语句。如果函数内部修改了结构体字段,这些修改会反映到最终的SQL中。

package main
import (
"fmt"
"time"
"xorm.io/xorm"
)
type User struct {
ID int64 `xorm:"pk autoincr"`
Name string `xorm:"varchar(50)"`
UpdatedAt time.Time `xorm:"updated"`
}
// BeforeUpdate 是钩子函数
func (u *User) BeforeUpdate() {
// 自动设置更新时间
u.UpdatedAt = time.Now()
fmt.Println("Hook: UpdatedAt set to", u.UpdatedAt)
}
func main() {
engine, err := xorm.NewEngine("mysql", "user:pass@tcp(127.0.0.1:3306)/db")
if err != nil {
panic(err)
}
defer engine.Close()
// 同步表结构
engine.Sync2(new(User))
// 创建用户
user := &User{Name: "Alice"}
engine.Insert(user)
// 更新用户,触发 BeforeUpdate
user.Name = "Bob"
affected, err := engine.ID(user.ID).Update(user)
if err != nil {
panic(err)
}
fmt.Printf("Updated %d rows\n", affected)
}
BeforeUpdate 与 Update 方法的交互细节
Update 方法支持通过 Cols 或 AllCols 控制更新列。钩子函数在列过滤之前执行,因此即使某些字段被排除在SQL之外,钩子中的逻辑仍会运行。若需根据条件跳过更新,可在钩子中返回错误或使用 Session 手动控制流程。

package main
import (
"fmt"
"time"
"xorm.io/xorm"
)
type Product struct {
ID int64 `xorm:"pk autoincr"`
Name string `xorm:"varchar(50)"`
Price float64 `xorm:"decimal(10,2)"`
Modified time.Time `xorm:"updated"`
}
func (p *Product) BeforeUpdate() {
if p.Price < 0 {
// 阻止非法价格更新
panic("price cannot be negative")
}
p.Modified = time.Now()
}
func main() {
engine, _ := xorm.NewEngine("sqlite3", ":memory:")
engine.Sync2(new(Product))
prod := &Product{Name: "Widget", Price: 10.0}
engine.Insert(prod)
// 正常更新
prod.Price = 15.0
engine.ID(prod.ID).Cols("price").Update(prod)
// 非法更新,触发 panic
prod.Price = -5.0
defer func() {
if r := recover(); r != nil {
fmt.Println("Caught error:", r)
}
}()
engine.ID(prod.ID).Cols("price").Update(prod)
}
基于 Update 方法中 Cols 参数对 BeforeUpdate 的影响
当使用 Cols 指定更新列时,BeforeUpdate 钩子依然会被调用,但只有被指定的列才会出现在生成的SQL中。这意味着钩子中可以安全地修改所有字段,但未被 Cols 包含的字段不会写入数据库。若需确保某些字段始终更新,应使用 AllCols 或在钩子中显式处理。


















