Use YAML

Import Maven Dependency

  1. <dependency>
  2. <groupId>org.apache.shardingsphere</groupId>
  3. <artifactId>shardingsphere-jdbc-core</artifactId>
  4. <version>${shardingsphere.version}</version>
  5. </dependency>

Configure Rule

ShardingSphere-JDBC YAML file consists of data sources, rules and properties configuration. The following example is the configuration of 2 databases and 2 tables, whose databases take module and split according to order_id, tables take module and split according to order_id.

Note: The example database connection pool is HikariCP, which can be replaced with other mainstream database connection pools according to business scenarios.

  1. # Configure actual data sources
  2. dataSources:
  3. # Configure the first data source
  4. ds0: !!com.zaxxer.hikari.HikariDataSource
  5. driverClassName: com.mysql.jdbc.Driver
  6. jdbcUrl: jdbc:mysql://localhost:3306/ds0
  7. username: root
  8. password:
  9. # Configure the second data source
  10. ds1: !!com.zaxxer.hikari.HikariDataSource
  11. driverClassName: com.mysql.jdbc.Driver
  12. jdbcUrl: jdbc:mysql://localhost:3306/ds1
  13. username: root
  14. password:
  15. rules:
  16. # Configure sharding rule
  17. - !SHARDING
  18. tables:
  19. # Configure t_order table rule
  20. t_order:
  21. actualDataNodes: ds${0..1}.t_order${0..1}
  22. # Configure database sharding strategy
  23. databaseStrategy:
  24. standard:
  25. shardingColumn: user_id
  26. shardingAlgorithmName: database_inline
  27. # Configure table sharding strategy
  28. tableStrategy:
  29. standard:
  30. shardingColumn: order_id
  31. shardingAlgorithmName: table_inline
  32. t_order_item:
  33. # Omit t_order_item table rule configuration ...
  34. # ...
  35. # Configure sharding algorithms
  36. shardingAlgorithms:
  37. database_inline:
  38. type: INLINE
  39. props:
  40. algorithm-expression: ds${user_id % 2}
  41. table_inline:
  42. type: INLINE
  43. props:
  44. algorithm-expression: t_order_${order_id % 2}
  1. // Create ShardingSphereDataSource
  2. DataSource dataSource = YamlShardingSphereDataSourceFactory.createDataSource(yamlFile);

Use ShardingSphereDataSource

The ShardingSphereDataSource created by YamlShardingSphereDataSourceFactory implements the standard JDBC DataSource interface. Developer can choose to use native JDBC or ORM frameworks such as JPA or MyBatis through the DataSource.

Take native JDBC usage as an example:

  1. DataSource dataSource = YamlShardingSphereDataSourceFactory.createDataSource(yamlFile);
  2. String sql = "SELECT i.* FROM t_order o JOIN t_order_item i ON o.order_id=i.order_id WHERE o.user_id=? AND o.order_id=?";
  3. try (
  4. Connection conn = dataSource.getConnection();
  5. PreparedStatement ps = conn.prepareStatement(sql)) {
  6. ps.setInt(1, 10);
  7. ps.setInt(2, 1000);
  8. try (ResultSet rs = preparedStatement.executeQuery()) {
  9. while(rs.next()) {
  10. // ...
  11. }
  12. }
  13. }