package main import ( "fmt" "gorm.io/driver/sqlite" "gorm.io/gorm" ) //type User struct { // ID uint `gorm:"primaryKey"` // Name string `gorm:"size:100"` // Email string `gorm:"size:100;unique"` // Age int //} // //type Account struct { // ID uint `gorm:"primaryKey"` // UserID uint // Balance int //} func main() { db, _ := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) db.AutoMigrate(&User{}, &Account{}) // 1. 手动事务 tx := db.Begin() // 创建用户 user := User{Name: "Alice", Email: "alice@example.com"} if err := tx.Create(&user).Error; err != nil { tx.Rollback() panic(err) } // 创建账户 account := Account{UserID: user.ID, Balance: 1000} if err := tx.Create(&account).Error; err != nil { tx.Rollback() panic(err) } // 提交事务 tx.Commit() fmt.Println("Transaction committed successfully!") // 2. 自动事务(推荐) err := db.Transaction(func(tx *gorm.DB) error { // 在事务中执行操作 user2 := User{Name: "Bob", Email: "bob@example.com"} if err := tx.Create(&user2).Error; err != nil { return err // 自动回滚 } account2 := Account{UserID: user2.ID, Balance: 2000} if err := tx.Create(&account2).Error; err != nil { return err // 自动回滚 } // 返回 nil 自动提交 return nil }) if err != nil { fmt.Println("Transaction failed:", err) } else { fmt.Println("Auto transaction committed successfully!") } }