当前位置:网站首页>Go GORM transaction instance analysis
Go GORM transaction instance analysis
2022-08-01 18:09:00 【Yisuyun】
Go GORM transaction instance analysis
This article mainly introduces the relevant knowledge of "Go GORM transaction instance analysis". The editor shows you the operation process through actual cases. The operation method is simple, fast and practical. I hope this "Go GORM transaction instance analysis"Transaction Case Analysis" article can help you solve the problem.
Disable default transactions
To ensure data consistency, GORM performs write operations (create, update, delete) within a transaction.If this is not required, you can disable it on initialization, which will give about 30%+ performance improvement.
// Disable db globally, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{ SkipDefaultTransaction: true,})// Persistent session modetx := db.Session(&Session{SkipDefaultTransaction: true})tx.First(&user, 1)tx.Find(&users)tx.Model(&user).Update("Age", 18)Transactions
To perform a series of operations in a transaction, the general flow is as follows:
db.Transaction(func(tx *gorm.DB) error { // Do some db operations in a transaction (from here you should use 'tx' instead of 'db') if err := tx.Create(&Animal{Name: "Giraffe"}).Error; err != nil { // Returning any error will rollback the transaction return err } if err := tx.Create(&Animal{Name:"Lion"}).Error; err != nil { return err } } // return nil Commit transaction return nil})Nested Transactions
GORM supports nested transactions, where you can roll back part of an operation performed within a larger transaction, example:
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") // Rollback user2 }) tx.Transaction(func(tx2 *gorm.DB) error { tx2.Create(&user3) return nil }) return nil})// Commit user1,user3Manual transactions
// Begin transaction tx := db.Begin()// Do some db operations in transaction (from here you should use 'tx' instead of 'db') tx.Create(...)// ...// Rollback transaction tx.Rollback()// Otherwise, commit transaction tx.Commit()
A special example
func CreateAnimals(db *gorm.DB) error { // Again, once the transaction starts, you should use tx to process the data 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}SavePoint, RollbackTo
GORM provides SavePoint, Rollbackto to provide savepoint and rollback to savepoint, for example:
tx := db.Begin()tx.Create(&user1)tx.SavePoint("sp1")tx.Create(&user2)tx.RollbackTo("sp1") // Rollbackuser2tx.Commit() // Commit user1The content of "Go GORM transaction instance analysis" is introduced here, thank you for reading.If you want to know more industry-related knowledge, you can pay attention to the Yisuyun industry information channel. The editor will update different knowledge points for you every day.
边栏推荐
- 快速抽取resnet_v2_152中间的特征层
- SQL的ROUND函数用法及其实例
- RecSys'22|CARCA: Cross-Attention-Aware Context and Attribute Recommendations
- gtk显示4通道rgba图像
- University of California | Inverse Reinforcement Learning from Different Third-Person Videos via Graph Abstraction
- EpiSci | Deep Reinforcement Learning for SoCs: Myth and Reality
- QPalette调色板、框架色彩填充
- 分布式消息队列平滑迁移技术实战
- C语言理论--笔试面试基础稳固
- 【Day_08 0426】两种排序方法
猜你喜欢

SRM供应商管理系统如何助力口腔护理企业实现采购战略的转型升级

移动端吸顶方案

opencv syntax Mat type summary

【Day_09 0427】 另类加法

三种方案解决:npm WARN config global --global, --local are deprecated. Use --location=global instead.

2022年SQL大厂高频实战面试题(详细解析)

OpenCV安装、QT、VS配置项目设置

B002 - Embedded Elderly Positioning Tracking Monitor

Leetcode72. Edit Distance

SQL窗口函数
随机推荐
极化微波成像概述3
el-form-item prop属性动态绑定不生效如何解决
OpenCV installation, QT, VS configuration project settings
【Error】Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘concat’)
Leetcode73. 矩阵置零
QT commonly used global macro definitions
计算IoU(D2L)
史上最全的Redis基础+进阶项目实战总结笔记
How to use the Golang coroutine scheduler scheduler
sql添加索引
bat 批示处理详解-2
TCP million concurrent server optimization parameters
OnePlus 10RT appears on Geekbench, product launch also seems to be approaching
CodeTON Round 2 (Div. 1 + Div. 2, Rated, Prizes!) 题解
消息模板占位符的使用
SQL函数 TO_DATE(一)
C#/VB.NET:从 PDF 文档中提取所有表格
浅谈大数据背景下数据库安全保障体系
B002 - Embedded Elderly Positioning Tracking Monitor
行业沙龙第二期丨如何通过供应链数字化业务协同,赋能化工企业降本增效?