Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to analyze gorm transactions

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)05/31 Report--

如何分析gorm事务,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

事务

gorm事务

1.禁用默认事务

SkipDefaultTransaction 为了确保数据一致性,GORM 会在事务里执行写入操作(创建、更新、删除)。 如果没有这方面的要求,您可以在初始化时禁用它,这将获得大约 30%+ 性能提升

// 全局禁用db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{ SkipDefaultTransaction: true,})// 持续会话模式tx := db.Session(&Session{SkipDefaultTransaction: true})tx.First(&user, 1)tx.Find(&users)tx.Model(&user).Update("Age", 18)2.事务

要在事务中执行一系列操作,一般流程如下:

db.Transaction(func(tx *gorm.DB) error { // 在事务中执行一些 db 操作(从这里开始,您应该使用 'tx' 而不是 'db') if err := tx.Create(&Animal{Name: "Giraffe"}).Error; err != nil { // 返回任何错误都会回滚事务 return err } if err := tx.Create(&Animal{Name: "Lion"}).Error; err != nil { return err } // 返回 nil 提交事务 return nil})3.嵌套事务

GORM 支持嵌套事务,您可以回滚较大事务内执行的一部分操作

DB.Transaction(func(tx *gorm.DB) error { tx.Create(&user1) tx.Transaction(func(tx2 *gorm.DB) error { tx2.Create(&user2) return errors.New("rollback user2") // 回滚 user2 }) tx.Transaction(func(tx2 *gorm.DB) error { tx2.Create(&user3) return nil }) return nil})// 仅提交 user1, user34.手动事务// 开始事务tx := db.Begin()// 在事务中执行一些 db 操作(从这里开始,您应该使用 'tx' 而不是 'db')tx.Create(...)// ...// 遇到错误时回滚事务tx.Rollback()// 否则,提交事务tx.Commit()5.一个特殊的示例func CreateAnimals(db *gorm.DB) error { // 再唠叨一下,事务一旦开始,你就应该使用 tx 处理数据 tx := db.Begin() defer func() { if r := recover(); r != nil { tx.Rollback() } }() if err := tx.Error; err != nil { return err } if err := tx.Create(&Animal{Name: "Giraffe"}).Error; err != nil { tx.Rollback() return err } if err := tx.Create(&Animal{Name: "Lion"}).Error; err != nil { tx.Rollback() return err } return tx.Commit().Error}6.SavePoint、RollbackTo

GORM 提供了 SavePoint、Rollbackto 来提供保存点以及回滚至保存点,例如

tx := DB.Begin()tx.Create(&user1)tx.SavePoint("sp1")tx.Create(&user2)tx.RollbackTo("sp1") // 回滚 user2tx.Commit() // 最终仅提交 user1看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注行业资讯频道,感谢您对的支持。

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report