使用 Spring Boot Starter

引入 Maven 依赖

  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. <!-- 使用 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. @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. }

使用分布式事务

  1. @Transactional
  2. @ShardingTransactionType(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. }