# dbtransaction **Repository Path**: aesoper/dbtransaction ## Basic Information - **Project Name**: dbtransaction - **Description**: No description available - **Primary Language**: Unknown - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2024-12-29 - **Last Updated**: 2024-12-29 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # DBTransaction Project ## 项目功能 该项目提供了一套数据库事务管理的解决方案,支持多种事务传播行为。主要功能包括: - 定义数据库事务接口 - 提供SQL和MongoDB的事务实现 - 支持多种事务传播行为,如Required、RequiresNew、Supports等 ## 安装步骤 1. **安装依赖** 确保你已经安装了Go语言环境,然后运行以下命令安装依赖: ```bash go get gitee.com/aesoper/dbtransaction ``` 2. **配置数据库** 根据需要配置你的数据库连接信息。 ## 使用说明 ### 初始化 根据你的数据库类型,初始化相应的事务管理器。 #### SQL 示例 ```go import ( "database/sql" _ "github.com/go-sql-driver/mysql" ) func main() { db, err := sql.Open("mysql", "user:password@/dbname") if err != nil { log.Fatal(err) } transaction := NewSQLTransaction(db) // 使用 transaction 进行事务操作 } ``` #### MongoDB 示例 ```go import ( "context" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) func main() { clientOptions := options.Client().ApplyURI("your-mongodb-uri") client, err := mongo.Connect(context.TODO(), clientOptions) if err != nil { log.Fatal(err) } transaction := NewMongoTransaction(client) // 使用 transaction 进行事务操作 } ``` ### 事务传播行为 本库支持以下事务传播行为: 1. **PropagationRequired**:如果当前没有事务,则创建一个新事务;如果已经存在事务,则加入该事务。 2. **PropagationRequiresNew**:总是创建一个新事务,如果当前存在事务,则挂起当前事务。 3. **PropagationSupports**:如果当前存在事务,则加入该事务;如果没有事务,则以非事务方式执行。 4. **PropagationNotSupported**:以非事务方式执行,如果当前存在事务,则挂起该事务。 5. **PropagationNever**:以非事务方式执行,如果当前存在事务,则抛出异常。 6. **PropagationMandatory**:必须在已存在的事务中执行,如果没有活动事务,则抛出异常。 7. **PropagationNested**:如果当前存在事务,则创建一个嵌套事务(对于支持的数据库);如果没有事务,则创建一个新事务。 ### 使用特定传播行为 ```go err := transaction.WithTransactionBehavior( context.TODO(), PropagationRequiresNew, func(ctx context.Context) error { // 在这里执行你的数据库操作 return nil }, ) ``` ### 事务操作 使用 `WithTransaction` 或 `WithTransactionBehavior` 方法执行事务。 ```go err := transaction.WithTransaction(context.TODO(), func(ctx context.Context) error { // 在这里执行你的数据库操作 return nil }) if err != nil { log.Fatal(err) } ``` ## 贡献 欢迎贡献代码!请提交 Pull Request 或报告问题。 ## 许可证 该项目基于 Apache 2.0 许可证进行分发。详细信息请参阅 LICENSE 文件。