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</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 the Narayana mode with XA transactions -->
  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

Perform the business logic using transactions

Sample

  1. // Use ShardingSphereDataSource to get a connection and perform transaction operations.
  2. try (Connection connection = dataSource.getConnection()) {
  3. connection.setAutoCommit(false);
  4. PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO t_order (user_id, status) VALUES (?, ?)");
  5. preparedStatement.setObject(1, 1000);
  6. preparedStatement.setObject(2, "init");
  7. preparedStatement.executeUpdate();
  8. connection.commit();
  9. }