This PR is a follow up to https://github.com/spring-projects/spring-framework/pull/30988. Goal is to add support for direct database operation routing in sharded databases in Spring JDBC.

This functionality is achieved by acquiring a shard connection through the JDBC API DataSource.createConnectionBuilder().shardingKey(key).build().

In this PR we will focus on one of the two approaches that were introduced in the previous PR.

We introduce a DataSource adapter class that applies sharding keys to every standard getConnection() call. The sharding keys are specified through a ShardingKeyProvider object.

Here's an example of how to use it:

ShardingKeyDataSourceAdapter dataSourceAdapter = new ShardingKeyDataSourceAdapter(dataSource);

dataSourceAdapter.setShardingKeyProvider(new ShardingKeyProvider() {
    public ShardingKey getShardingKey() throws SQLException {
        // Example: The sharding key is derived from the user name.
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        return dataSource.createShardingKeyBuilder().subKey(name, JDBCType.VARCHAR).build();
    }

    public ShardingKey getSuperShardingKey() throws SQLException {
        return null;
    }
});

JdbcTemplate shardingJdbcTemplate = new JdbcTemplate(dataSourceAdapter);

// The SQL query will be executed directly in the shard corresponding 
// to the sharding key returned from the ShardingKeyProvider.getShardingKey() method.
shardingJdbcTemplate.execute(SQL);

Comment From: snicoll

@meedbek thanks for the PR, but I think it would only be actionable if we decide to merge https://github.com/spring-projects/spring-framework/pull/30988, which we haven't. Am I missing something?

Comment From: meedbek

@meedbek thanks for the PR, but I think it would only be actionable if we decide to merge #30988, which we haven't. Am I missing something?

I am taking over @Anir-ln work on the feature that's why I opened a new PR. I am focusing on one side of the feature for now, I will look into the rest later.

Comment From: snicoll

What do you mean by "taking over"? You mean replacing? If so, then there should be some discussion to close the other PR then.

Comment From: meedbek

What do you mean by "taking over"? You mean replacing? If so, then there should be some discussion to close the other PR then.

@snicoll thank you for the reply, it's done. The other PR has been closed.

Comment From: jeandelavarene

Hallo @jhoeller, we would like to have a meeting with you to review the comments you made in the older PR https://github.com/spring-projects/spring-framework/pull/30988 regarding transactions. Would that be possible? If so, how to proceed? Thank you.