Dynamic Database Switching in MyBatis Using SQL Source Decoration
This article explains how to implement dynamic database switching in MyBatis by intercepting and modifying SQL statements to prepend database names to table names, using JSqlParser and MyBatis interceptors.
This article addresses the challenge of querying data across multiple databases with identical table structures within a single data source. The author proposes a solution that avoids introducing complex sharding frameworks by intercepting SQL execution and dynamically prepending database names to table names.
The core implementation uses MyBatis interceptors and the JSqlParser library. The approach involves creating an abstract interceptor class that decorates the SqlSource object using the decorator pattern. This decoration intercepts the getBoundSql method, allowing SQL modification before execution.
The SqlSourceDecorator class performs the key operations: it retrieves the original SQL, determines the appropriate database name based on business parameters, uses JSqlParser to identify all table names in the SQL, and then prepends the database name to each table name. Reflection is used to modify the SQL string within the BoundSql object.
The abstract interceptor provides reusable methods for decorating SqlSource objects and handling the database name switching logic. Concrete interceptors extend this abstract class and implement the specific database name determination logic based on business requirements.
The solution is configured as a MyBatis interceptor, enabling dynamic database switching without requiring multiple data source configurations or complex sharding frameworks. This approach is particularly useful for scenarios like logistics sorting where data is partitioned across multiple databases with identical schemas.
JD Tech Talk
Official JD Tech public account delivering best practices and technology innovation.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.