Use Spring Boot Starter

Background

ShardingSphere-JDBC can be used through spring boot starter.

Prerequisites

Introducing Maven dependency

  1. <dependency>
  2. <groupId>org.apache.shardingsphere</groupId>
  3. <artifactId>shardingsphere-jdbc-core-spring-boot-starter</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 Type
  2. Use distributed transactions

Sample

Configure the transaction Type

  1. @Configuration
  2. @EnableTransactionManagement
  3. public class TransactionConfiguration {
  4. @Bean
  5. public PlatformTransactionManager txManager(final DataSource dataSource) {
  6. return new DataSourceTransactionManager(dataSource);
  7. }
  8. @Bean
  9. public JdbcTemplate jdbcTemplate(final DataSource dataSource) {
  10. return new JdbcTemplate(dataSource);
  11. }
  12. }

Use distributed transactions

  1. @Transactional
  2. @ShardingSphereTransactionType(TransactionType.XA) // 支持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. }