使用 Java API

引入 Maven 依赖

  1. <dependency>
  2. <groupId>org.apache.shardingsphere</groupId>
  3. <artifactId>shardingsphere-jdbc-core</artifactId>
  4. <version>${shardingsphere.version}</version>
  5. </dependency>
  6. <!-- 使用 XA 事务时,需要引入此模块 -->
  7. <dependency>
  8. <groupId>org.apache.shardingsphere</groupId>
  9. <artifactId>shardingsphere-transaction-xa-core</artifactId>
  10. <version>${shardingsphere.version}</version>
  11. </dependency>
  12. <!-- 使用 BASE 事务时,需要引入此模块 -->
  13. <dependency>
  14. <groupId>org.apache.shardingsphere</groupId>
  15. <artifactId>shardingsphere-transaction-base-seata-at</artifactId>
  16. <version>${shardingsphere.version}</version>
  17. </dependency>

使用分布式事务

  1. TransactionTypeHolder.set(TransactionType.XA); // 支持 TransactionType.LOCAL, TransactionType.XA, TransactionType.BASE
  2. try (Connection conn = dataSource.getConnection()) { // 使用 ShardingSphereDataSource
  3. conn.setAutoCommit(false);
  4. PreparedStatement ps = conn.prepareStatement("INSERT INTO t_order (user_id, status) VALUES (?, ?)");
  5. ps.setObject(1, 1000);
  6. ps.setObject(2, "init");
  7. ps.executeUpdate();
  8. conn.commit();
  9. }