ibatis替换数据库源
#替换其它数据库连接进入ibatis SqlSessionFactory
ibatis 通过配置建立SqlSessionFactory 来获取Session 对数据库进行操作
某些情况配置文件影响灵活性
比如当数据库无法连接时企图建立本地文件数据库进行替代
或者希望通过服务器界面进行启动前配置
以上情况 可以修改配置文件中的Environment 的Datasource 的属性完成
但是配置文件封装在打包内部 或者在远程的情况不容易进行修改
SqlSessionFactory 已经持有固定的配置 不提供函数修改已经加载的特定资源
以下代码将一个本地的Sqlite 数据库塞入 加载xml配置文件的SqlSessionFactory 以供大家进行参照
具体就是定位到配置解析的某个字段 然后反射用一个其它的数据源进行替换
很简单
希望能帮到缆子间歇性疼痛的读者
static {
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
Reader inputStreamReader = new InputStreamReader(inputStream);
XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, null, null);
Configuration configuration = parser.parse();
Environment environment = configuration.getEnvironment();
DataSource dataSource = environment.getDataSource();
try {
Connection connection = dataSource.getConnection();//detect the connect which generate by url in xml config<mybatis-squlite-config.xml> is valid
connection.close();
} catch (SQLException throwables) {
// SQLiteDataSource sqLiteDataSource = new SQLiteDataSource(new SQLiteConfig());
Field dataSource_field = environment.getClass().getDeclaredField("dataSource");
dataSource_field.setAccessible(true);
dataSource_field.set(environment, getDataSource(System.getProperty("user.dir")));
throwables.printStackTrace();
}
sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
} catch (IOException | NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
}
static DataSource getDataSource(String address) //ass your faver generate a dataSource present interview of a database source
{
Connection connection = ToolKitSqliteShieldPumpTest.generateDataBase(address);
return new DataSource() {
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return null;
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false;
}
@Override
public Connection getConnection() throws SQLException {
return connection;
}
@Override
public Connection getConnection(String username, String password) throws SQLException {
return connection;
}
@Override
public PrintWriter getLogWriter() throws SQLException {
return null;
}
@Override
public void setLogWriter(PrintWriter out) throws SQLException {
}
@Override
public void setLoginTimeout(int seconds) throws SQLException {
}
@Override
public int getLoginTimeout() throws SQLException {
return 0;
}
@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
return null;
}
};
}