I\'ve read many questions and answers about dynamic datasource routing and have implemented a solution using AbstractRoutingDataSource and another(see below). T
Given that you do not specify the DBMS, here is a high-level idea that may help.
(Although I am using Spring Data JDBC-ext as reference, same approach can be easily adopted by using general AOP)
Please refer to http://docs.spring.io/spring-data/jdbc/docs/current/reference/html/orcl.connection.html , Section 8.2
In Spring Data JDBC-ext, there is ConnectionPreparer that can allow you to run arbitrary SQLs when you acquire a Connection from DataSource. You can simply execute the commands to switch schema (e.g. ALTER SESSION SET CURRENT SCHEMA = 'schemaName' in Oracle, using schemaName for Sybase etc).
e.g.
package foo;
import org.springframework.data.jdbc.support.ConnectionPreparer;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
public class SwitchSchemaConnectionPreparer implements ConnectionPreparer {
public Connection prepare(Connection conn) throws SQLException {
String schemaName = whateverWayToGetTheScehmaToSwitch();
CallableStatement cs = conn.prepareCall("ALTER SESSION SET CURRENT SCHEMA " + scehmaName);
cs.execute();
cs.close();
return conn;
}
}
In App Context config