Use Spring Namespace

Background

ShardingSphere-JDBC can be used through spring namespace.

Prerequisites

Introducing Maven denpendency

  1. <dependency>
  2. <groupId>org.apache.shardingsphere</groupId>
  3. <artifactId>shardingsphere-jdbc-core-spring-namespace</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. Configure the transaction manager
  2. Use distributed transactions

Sample

Configure the transaction manager

  1. <!-- Configuration of ShardingDataSource -->
  2. <!-- ... -->
  3. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  4. <property name="dataSource" ref="shardingDataSource" />
  5. </bean>
  6. <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  7. <property name="dataSource" ref="shardingDataSource" />
  8. </bean>
  9. <tx:annotation-driven />
  10. <!-- Enable automatic scanning of @ShardingSphereTransactionType annotation and use Spring's native AOP for class and method enhancements -->
  11. <sharding:tx-type-annotation-driven />

Use distributed transactions

  1. @Transactional
  2. @ShardingSphereTransactionType(TransactionType.XA) // support TransactionType.LOCAL, TransactionType.XA, TransactionType.BASE
  3. public void insert() {
  4. jdbcTemplate.execute("INSERT INTO t_order (user_id, status) VALUES (?, ?)", (PreparedStatementCallback<Object>) ps -> {
  5. ps.setObject(1, i);
  6. ps.setObject(2, "init");
  7. ps.executeUpdate();
  8. });
  9. }