Overview

Java API is the basic configuration methods in ShardingSphere-JDBC, and other configurations will eventually be transformed into Java API configuration methods.

The Java API is the most complex and flexible configuration method, which is suitable for the scenarios requiring dynamic configuration through programming.

Usage

Import Maven Dependency

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

Create Data Source

ShardingSphere-JDBC Java API consists of database name, mode configuration, data source map, rule configurations and properties.

The ShardingSphereDataSource created by ShardingSphereDataSourceFactory implements the standard JDBC DataSource interface.

  1. String databaseName = "foo_schema"; // Indicate logic database name
  2. ModeConfiguration modeConfig = ... // Build mode configuration
  3. Map<String, DataSource> dataSourceMap = ... // Build actual data sources
  4. Collection<RuleConfiguration> ruleConfigs = ... // Build concentrate rule configurations
  5. Properties props = ... // Build properties
  6. DataSource dataSource = ShardingSphereDataSourceFactory.createDataSource(databaseName, modeConfig, dataSourceMap, ruleConfigs, props);

Please refer to Mode Configuration for more mode details.

Please refer to Data Source Configuration for more data source details.

Please refer to Rules Configuration for more rule details.

Use Data Source

Developer can choose to use native JDBC or ORM frameworks such as JPA, Hibernate or MyBatis through the DataSource.

Take native JDBC usage as an example:

  1. // Create ShardingSphereDataSource
  2. DataSource dataSource = ShardingSphereDataSourceFactory.createDataSource(databaseName, modeConfig, dataSourceMap, ruleConfigs, props);
  3. 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=?";
  4. try (
  5. Connection conn = dataSource.getConnection();
  6. PreparedStatement ps = conn.prepareStatement(sql)) {
  7. ps.setInt(1, 10);
  8. ps.setInt(2, 1000);
  9. try (ResultSet rs = preparedStatement.executeQuery()) {
  10. while(rs.next()) {
  11. // ...
  12. }
  13. }
  14. }