Logo
Java API

Introduction #

Java API is the basis for all configuration methods in DBPlusEngine-Driver and all other configurations will eventually translate into the Java API configuration method.

Java API is the most flexible configuration method and is suitable for use in scenarios where dynamic configuration is required programmatically.

Usage steps #

Introduce Maven dependency #

<dependency>
    <groupId>org.apache.shardingsphere</groupId>
    <artifactId>shardingsphere-jdbc-core</artifactId>
    <version>${shardingsphere.version}</version>
</dependency>

Build data sources #

Java API of the DBPlusEngine-Driver consists of a Schema name, a runtime schema, a collection of data sources, a collection of rules, and a configuration of properties.

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

String schemaName = "foo_schema"; // 指定逻辑 Schema 名称
ModeConfiguration modeConfig = ... // 构建运行模式
Map<String, DataSource> dataSourceMap = ... // 构建真实数据源
Collection<RuleConfiguration> ruleConfigs = ... // 构建具体规则
Properties props = ... // 构建属性配置
DataSource dataSource = ShardingSphereDataSourceFactory.createDataSource(schemaName, modeConfig, dataSourceMap, ruleConfigs, props);

SeeMode Configuration for details of the mode.

SeeData Source Configuration for details of the data source.

SeeRule Configuration for details of rules.

Usage data sources #

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

As an example of how native JDBC can be used:

// Create ShardingSphereDataSource
DataSource dataSource = ShardingSphereDataSourceFactory.createDataSource(schemaName, modeConfig, dataSourceMap, ruleConfigs, props);

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=?";
try (
        Connection conn = dataSource.getConnection();
        PreparedStatement ps = conn.prepareStatement(sql)) {
    ps.setInt(1, 10);
    ps.setInt(2, 1000);
    try (ResultSet rs = preparedStatement.executeQuery()) {
        while(rs.next()) {
            // ...
        }
    }
}