<dependency><groupId>org.apache.shardingsphere</groupId><artifactId>shardingsphere-jdbc-core-spring-namespace</artifactId><version>${shardingsphere.version}</version></dependency><!-- import if using XA transaction --><dependency><groupId>org.apache.shardingsphere</groupId><artifactId>shardingsphere-transaction-xa-core</artifactId><version>${shardingsphere.version}</version></dependency><!-- import if using BASE transaction --><dependency><groupId>org.apache.shardingsphere</groupId><artifactId>shardingsphere-transaction-base-seata-at</artifactId><version>${shardingsphere.version}</version></dependency>
Configure Transaction Manager
<!-- ShardingDataSource configuration --><!-- ... --><beanid="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><propertyname="dataSource"ref="shardingDataSource"/></bean><beanid="jdbcTemplate"class="org.springframework.jdbc.core.JdbcTemplate"><propertyname="dataSource"ref="shardingDataSource"/></bean><tx:annotation-driven/><!-- Enable auto scan @ShardingSphereTransactionType annotation to inject the transaction type before connection created --><sharding:tx-type-annotation-driven/>
Use Distributed Transaction
@Transactional@ShardingSphereTransactionType(TransactionType.XA)// Support TransactionType.LOCAL, TransactionType.XA, TransactionType.BASE
publicvoidinsert(){
jdbcTemplate.execute("INSERT INTO t_order (user_id, status) VALUES (?, ?)",(PreparedStatementCallback<Object>) ps ->{
ps.setObject(1, i);
ps.setObject(2,"init");
ps.executeUpdate();});}