Your Question

我正在使用 GIN 框架和 Gorm 写restful api(结构分有controller、usecase、repository、domain), 但是发现如果我在其中一个API中的函数中使用transaction(事务),在 commit/ roll back后, 当客端重新呼叫别的api的时候,库的connection(连接)并不会自动初始化,导致sql transaction has already been committed or rolled back

我知道一个事务只能使用一次commit/ rollback, 那么我这个情况该怎么处理? 谢谢

The document you expected this should be explained

Expected answer

Comment From: a631807682

Do not reuse the same instance to process transactions, you can use Session to create another instance. https://gorm.io/docs/v2_release_note.html#Method-Chain-Safety-x2F-Goroutine-Safety

    tx1 := DB.Begin()
    tx1.Create(&User{Name: "jinzhu"})
    tx1.Commit()

    tx1.Create(&User{Name: "jinzhu"}) // fail

    DB.Create(&User{Name: "jinzhu"})  // success

Comment From: kentestforjob

https://gorm.io/docs/v2_release_note.html#Method-Chain-Safety-x2F-Goroutine-Safety

@a631807682 I have called the first Api. And then call the second Api (different route and not in same function) Why it still has such problem? I need to create "New Session Method" for each sql query?

The following is my dummy example, can you help me to take a look on it? thanks!!! https://github.com/go-gorm/gorm/issues/6244