普通事务/嵌套事务
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| type TMG struct { ID uint Name string }
func TestTransaction() { Db.AutoMigrate(&TMG{}) flag := false if err := Db.Transaction(func(tx *gorm.DB) error { tx.Create(&TMG{Name: "汉子"}) tx.Create(&TMG{Name: "威武"}) tx.Transaction(func(tx *gorm.DB) error { tx.Create(&TMG{Name: "汉子2"}) return nil }) if flag { return nil } else { return errors.New("出错了") } }); err != nil { fmt.Println("事务出错了", err) } }
|
手动事务
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| type TMG struct { ID uint Name string }
func TestTransaction() { Db.AutoMigrate(&TMG{}) tx := Db.Begin() tx.Create(&TMG{Name: "L1212"}) tx.Commit() }
|
记录回滚点
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| type TMG struct { ID uint Name string }
func TestTransaction() { Db.AutoMigrate(&TMG{}) tx := Db.Begin() tx.Create(&TMG{Name: "aa"}) tx.Create(&TMG{Name: "bb"}) tx.SavePoint("sp1") tx.Create(&TMG{Name: "cc"}) tx.RollbackTo("sp1") tx.Commit() }
|
API (Application Programming Interface)