Change database schema during runtime based on logged in user

后端 未结 2 1283
暗喜
暗喜 2020-12-02 09:13

I\'ve read many questions and answers about dynamic datasource routing and have implemented a solution using AbstractRoutingDataSource and another(see below). T

2条回答
  •  我在风中等你
    2020-12-02 10:07

    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

    
        
    
    
    
        
            
        
    
    

提交回复
热议问题