We hope that after reading the Sharding-JDBC series of articles, readers can master the core knowledge of database and table division, understand the implementation principle, and realize the simple embedded database and table component by themselves. In addition, we also hope that readers can think why database and table division? As well as the problems brought by the sub-database sub-table? And how to deal with this kind of question, which is also a common knowledge in the interview.

1. JDBC standard interface

JDBC is one of the STANDARD specifications of J2EE, J2EE is to standardize JAVA to solve the development of a series of standards for enterprise applications, JDBC is no exception.

JDBC is the standard Java API for database-independent connections between the Java programming language and databases. In other words, using the JAVA language to connect to a database for operations requires the JDBC API.

A unified JDBC API hides the details of the underlying database and allows consistent encoding (across databases) to operate on the database. JAVA is decoupled from database access connections through JDBC, which can be developed independently of each other and used in combination.

Each database provides the driver to achieve THE JDBC standard API, access to the database, the application does not need to access different databases in the code layer for adaptation

2. Implementation of four JDBC interfaces

2.1, the Connection

Sharding Connection implements the standard JDBC Connection interface. First look at the class diagram

Abstract class AbstractUnsupportedOperationConnection Connection freestanding interface, which does not support the Connection in sharding approach in such exceptions

 @Override
    public final CallableStatement prepareCall(final String sql) throws SQLException {
        throw new SQLFeatureNotSupportedException("prepareCall");
    }
.  @Override  public final CallableStatement prepareCall(final String sql, final int resultSetType, final int resultSetConcurrency) throws SQLException {  throw new SQLFeatureNotSupportedException("prepareCall");  } Copy the code

AbstractConnectionAdapter implements the function logic, including creating a connection, close the connection, etc., the class has three need to master in place, people feel good, can improve coding skills

  • ForceExecuteTemplate classes provide execution parameter template method is a collection and callbackForceExecuteCallback callback interface
    public void execute(final Collection<T> targets, final ForceExecuteCallback<T> callback) throws SQLException {
        Collection<SQLException> exceptions = new LinkedList<>();
        for (T each : targets) {
            try {
                callback.execute(each);
 } catch (final SQLException ex) {  exceptions.add(ex);  }  }  throwSQLExceptionIfNecessary(exceptions);  } Copy the code

See for yourself the benefits of writing like this.

  • RootInvokeHook Hook method

SPI registration hook method, record the call process, can be implemented in a variety of ways, this extension method is flexible, easy to expand, can be easily adapted to different platforms for call chain information collection.

public interface RootInvokeHook {
    
    / * *     * Handle when root invoke started.
* /
 void start(a);   / * * * Handle when root invoke finished.  *  * @param connectionCount connection count * /  void finish(int connectionCount); }  Copy the code

SPI implementation

public final class SPIRootInvokeHook implements RootInvokeHook {
    
    private final Collection<RootInvokeHook> rootInvokeHooks = NewInstanceServiceLoader.newServiceInstances(RootInvokeHook.class);
    
    static {
 NewInstanceServiceLoader.register(RootInvokeHook.class);  }   @Override  public void start(a) {  for (RootInvokeHook each : rootInvokeHooks) {  each.start();  }  }   @Override  public void finish(final int connectionCount) {  for (RootInvokeHook each : rootInvokeHooks) {  each.finish(connectionCount);  }  } } Copy the code

The process starts calling

 protected AbstractConnectionAdapter(a) {
        rootInvokeHook.start();
    }
Copy the code

End of the process

 public final void close(a) throws SQLException {
        closed = true;
        MasterVisitedManager.clear();
        TransactionTypeHolder.clear();
        int connectionSize = cachedConnections.size();
 try {  forceExecuteTemplateForClose.execute(cachedConnections.entries(), new ForceExecuteCallback<Entry<String, Connection>>() {   @Override  public void execute(final Entry<String, Connection> cachedConnections) throws SQLException {  cachedConnections.getValue().close();  }  });  } finally {  cachedConnections.clear();  rootInvokeHook.finish(connectionSize);  }  } Copy the code

You can use hook methods to count SQL execution time, etc., this extension design method can be learned.

2.2, the Statement

ShardingStatement implements the Statement interface in Sharding, and shardingPrepareStatement implements PreparedStatement

The functions of abstract classes are basically similar to those of Connection. We will not repeat them here, but mainly refer to shardingStatement and SharingPrepareStatement

2.3, the ResultSet

ShardingResultSet in Sharding-JDBC implements the ResultSet interface, which mainly processes result sets. A single ResultSet operated in a single library scenario may return multiple results, requiring result sets to be processed

ShardingResultSet has a member variable

private final MergedResult mergeResultSet
Copy the code

This is an interface that works with different result sets, so you can see what it means

The details are not analyzed here, and the results set will be analyzed in a special section later. Result set and table middleware is a difficulty in implementation.

2.4 the DataSource,

ShardingDataSource implements the DataSource interface and provides the connection method

    @Override
    public final ShardingConnection getConnection(a) {
        return new ShardingConnection(getDataSourceMap(), runtimeContext, TransactionTypeHolder.get());
    }
Copy the code

3. Conclusion

The main implementation of sharding-JDBC standard JDBC protocol to do the overall introduction, as well as sharding-JDBC entry, this is the implementation of an ORM essential knowledge points, such as Mybatis, The following chapter will be on the sub-library sub-table routing module, SQL execution module, result set and module of the source code will be detailed analysis, I hope readers after reading this series of articles, you can achieve a simplified version of the sub-library sub-table components.