Use Java API

Background

With ShardingSphere-JDBC, XA and BASE mode transactions can be used through the API.

Prerequisites

Introducing Maven dependency

  1. <dependency>
  2. <groupId>org.apache.shardingsphere</groupId>
  3. <artifactId>shardingsphere-jdbc-core</artifactId>
  4. <version>${shardingsphere.version}</version>
  5. </dependency>
  6. <!-- This module is required when using XA transactions -->
  7. <dependency>
  8. <groupId>org.apache.shardingsphere</groupId>
  9. <artifactId>shardingsphere-transaction-xa-core</artifactId>
  10. <version>${shardingsphere.version}</version>
  11. </dependency>
  12. <!-- This module is required when using XA's Narayana mode -->
  13. <dependency>
  14. <groupId>org.apache.shardingsphere</groupId>
  15. <artifactId>shardingsphere-transaction-xa-narayana</artifactId>
  16. <version>${project.version}</version>
  17. </dependency>
  18. <!-- This module is required when using BASE transactions -->
  19. <dependency>
  20. <groupId>org.apache.shardingsphere</groupId>
  21. <artifactId>shardingsphere-transaction-base-seata-at</artifactId>
  22. <version>${shardingsphere.version}</version>
  23. </dependency>

Procedure

  1. Set the transaction type
  2. Perform the business logic

Sample

  1. TransactionTypeHolder.set(TransactionType.XA); // support TransactionType.LOCAL, TransactionType.XA, TransactionType.BASE
  2. try (Connection conn = dataSource.getConnection()) { // use 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. }