mysql動態連線資料庫
阿新 • • 發佈:2019-02-06
1.配置xml檔案
applicationContext.xml <bean id="defaultDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${default.driver}" /> <property name="url" value="${default.url}" /> <property name="username" value="${default.username}" /> <property name="password" value="${default.password}" /> </bean> <bean id="dataSource" class="com.ceict.ems.common.db.DynamicDataSource"> <property name="targetDataSources"> <map> <entry key="default" value-ref="defaultDataSource" /> </map> </property> </bean>
2.編寫動態連線的介面:
3.測試:public class DynamicDataSource extends AbstractRoutingDataSource { private Map<Object, Object> _targetDataSources; @Override protected Object determineCurrentLookupKey() { return DataSourceContextHolder.getDataSource(); } public void setTargetDataSources(Map<Object, Object> targetDataSources) { this._targetDataSources = targetDataSources; super.setTargetDataSources(targetDataSources); afterPropertiesSet(); } public String getDbtype(String key) { String driver = ((BasicDataSource) _targetDataSources.get(key)) .getDriverClassName(); if ("oracle.jdbc.driver.OracleDriver".equals(driver)) { return "oracle"; } else if ("com.mysql.jdbc.Driver".equals(driver)) { return "mysql"; } return null; } public void addTargetDataSource(String key, DataSource dataSource) { _targetDataSources.put(key, dataSource); this.setTargetDataSources(_targetDataSources); } public static DataSource createDataSource(String driverClassName, String url, String username, String password) { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(driverClassName); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); dataSource.setTestWhileIdle(true); if ("oracle.jdbc.driver.OracleDriver".equals(driverClassName)) { dataSource.setValidationQuery("SELECT 1 FROM DUAL"); } else if ("com.mysql.jdbc.Driver".equals(driverClassName)) { dataSource.setValidationQuery("SELECT NOW()"); } return dataSource; } }
DynamicDataSource dynamicDataSource = ApplicationUtil .getBean(DynamicDataSource.class); BasicDataSource dataSource = DynamicDataSource.createDataSource(driverClassName,url,userName,password) dynamicDataSource.addTargetDataSource("dbkey", dataSource ); DataSourceContextHolder.setDataSource("dbkey"); // 通過以上語句可以將資料庫連線配置修改為當前設定的 //執行自己的DAO方法 DataSourceContextHolder.clearDataSource();//恢復資料庫的配置為applicationContext.xml預設的配置