普通事务/嵌套事务

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
}

// 事务一次begin一次commit
func TestTransaction() {
Db.AutoMigrate(&TMG{})
// 开启事务
tx := Db.Begin()
// 创建记录
tx.Create(&TMG{Name: "L1212"})
// 提交事务
tx.Commit()
}

// Db.Rollback() 回滚事务

记录回滚点

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") // 1.
tx.Create(&TMG{Name: "cc"}) // 2.
tx.RollbackTo("sp1") // 3.
// 提交事务
tx.Commit()
}
// 这里的1.2.3.的三行将不会被执行

API (Application Programming Interface)