日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

动态切换数据源(spring+hibernate)

發(fā)布時(shí)間:2025/3/17 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 动态切换数据源(spring+hibernate) 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

起因:在當(dāng)前我手上的一個(gè)項(xiàng)目中需要多個(gè)數(shù)據(jù)源,并且來自于不同類型的數(shù)據(jù)庫... 因?yàn)楹芏鄽v史原因.這個(gè)項(xiàng)目的住數(shù)據(jù)源是MySQL,整個(gè)系統(tǒng)的CURD都是操作的這個(gè)數(shù)據(jù)庫.

但是還有另外兩個(gè)用于數(shù)據(jù)采集的數(shù)據(jù)庫: MSSQL,ACCESS.還好只是用于數(shù)據(jù)采集,在事務(wù)上可以不要跨數(shù)據(jù)庫了,這一點(diǎn)節(jié)省了好多的工作量.

環(huán)境:我搭建的測試環(huán)境是 spring2.5.6+hibernate3.2 思路:動態(tài)切換數(shù)據(jù)源確切的來說是在同一類型數(shù)據(jù)庫的情況下的。意思就是說 , 在系統(tǒng)中的使用的數(shù)據(jù)庫分布在多臺數(shù)據(jù)庫服務(wù)器或者在同臺服務(wù)器上的多個(gè)數(shù)據(jù)庫. 在運(yùn)行時(shí)期間根據(jù)某種標(biāo)識符來動態(tài)的選擇當(dāng)前操作的數(shù)據(jù)庫. 1.數(shù)據(jù)源是相同類型的數(shù)據(jù)庫: 一個(gè)SessionFactory+動態(tài)數(shù)據(jù)源+一個(gè)事務(wù)管理器 2.數(shù)據(jù)源是不同類型的數(shù)據(jù)庫: 根據(jù)類型 配置多套SessionFactory 模擬:兩個(gè)mysql數(shù)據(jù)源+一個(gè)Access數(shù)據(jù)源 實(shí)現(xiàn) 1.切換數(shù)據(jù)源需要標(biāo)識符,標(biāo)識符是Object類型 package lhp.example.context;public enum DBType { dataSource1, dataSource2;} 2.然后創(chuàng)建一個(gè)用于切換數(shù)據(jù)源(設(shè)置或者獲得上下文)的工具類 package lhp.example.context;public class ContextHolder {private static final ThreadLocal<Object> holder = new ThreadLocal<Object>();public static void setDbType(DBType dbType) {holder.set(dbType);}public static DBType getDbType() {return (DBType) holder.get();}public static void clearDbType() {holder.remove();} } 3.創(chuàng)建動態(tài)數(shù)據(jù)源類,繼承org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource這個(gè)類. package lhp.example.context;import java.util.logging.Logger;import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;public class DynamicDataSource extends AbstractRoutingDataSource {public static final Logger logger = Logger.getLogger(DynamicDataSource.class.toString());@Overrideprotected Object determineCurrentLookupKey() {DBType key = ContextHolder.getDbType();//獲得當(dāng)前數(shù)據(jù)源標(biāo)識符//logger.info("當(dāng)前數(shù)據(jù)源 :" + key);return key;}} 4.然后配置多個(gè)數(shù)據(jù)源 <!-- 數(shù)據(jù)源1 : mysql --><bean id="dataSource1" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="com.mysql.jdbc.Driver" /><property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/dec" /><property name="user" value="root" /><property name="password" value="" /></bean><!-- 數(shù)據(jù)源2 : mysql --><bean id="dataSource2" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="com.mysql.jdbc.Driver" /><property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/lms" /><property name="user" value="root" /><property name="password" value="" /></bean><!-- 數(shù)據(jù)源3 : access --><bean id="dataSource3" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="sun.jdbc.odbc.JdbcOdbcDriver" /><property name="jdbcUrl" value="jdbc:odbc:accessTest" /><property name="user" value="administrator" /><property name="password" value="XLZX0309" /></bean><!-- mysql 動態(tài)數(shù)據(jù)源設(shè)置--><bean id="mysqlDynamicDataSource" class="lhp.example.context.DynamicDataSource"><property name="targetDataSources"><!-- 標(biāo)識符類型 --><map key-type="lhp.example.context.DBType"><entry key="dataSource1" value-ref="dataSource1" /><entry key="dataSource2" value-ref="dataSource2" /></map></property><property name="defaultTargetDataSource" ref="dataSource1" /></bean> 5.配置sessionFactory <!-- mysql sessionFactory --><bean id="mysqlSessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"><property name="dataSource" ref="mysqlDynamicDataSource" /><property name="hibernateProperties"><props><prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop><prop key="hibernate.show_sql">true</prop><prop key="hibernate.hbm2ddl.auto">update</prop><!--create validate --><prop key="hibernate.query.substitutions">true 1, false 0</prop></props></property></bean><!-- access sessionFactory --><bean id="aceessSessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"><property name="dataSource" ref="dataSource3" /><property name="hibernateProperties"><props><!-- access 語法和MSSQL相似 所以用的MSSQL方言,或者可以使用第三方方言 --><prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop><prop key="hibernate.jdbc.batch_size">30</prop><prop key="hibernate.jdbc.fetch_size">50</prop><prop key="hibernate.show_sql">true</prop><prop key="hibernate.format_sql">false</prop><prop key="hibernate.hbm2ddl.auto">update</prop><!--create validate --><prop key="hibernate.query.substitutions">true 1, false 0</prop><prop key="hibernate.cglib.use_reflection_optimizer">true</prop><!-- <prop key="hibernate.cache.use_second_level_cache">true</prop> --><!-- <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop> --><!-- <prop key="hibernate.cache.use_query_cache">true</prop> --><!-- <prop key="hibernate.generate_statistics">true</prop> --><!-- <prop key="hibernate.cache.provider_configuration_file_resource_path">classpath:ehcache.xml</prop> --></props></property></bean> 6.測試用例 package lhp.example.junit;import static org.junit.Assert.*; import java.sql.DatabaseMetaData; import lhp.example.context.ContextHolder; import lhp.example.context.DBType; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.junit.Before; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;public class ServiceTest {private ApplicationContext context;//三個(gè)數(shù)據(jù)源的URLprivate String dataSource1_URL = "jdbc:mysql://127.0.0.1:3306/dec";private String dataSource2_URL = "jdbc:mysql://127.0.0.1:3306/lms";private String dataSource3_URL = "jdbc:odbc:accessTest";private SessionFactory mysqlSessionFactory;private SessionFactory aceessSessionFactory;@Beforepublic void setUp() throws Exception {// 選擇數(shù)據(jù)源初始化spring ContextHolder.setDbType(DBType.dataSource1);// String[] xmlFiles = new String[] { "applicationContext-dataSource.xml","applicationContext-hibernate.xml","applicationContext-spring.xml" };// context = new ClassPathXmlApplicationContext(xmlFiles);// mysqlSessionFactory = (SessionFactory) context.getBean("mysqlSessionFactory");aceessSessionFactory = (SessionFactory) context.getBean("aceessSessionFactory");}@SuppressWarnings("deprecation")@Testpublic void mysqlDataSourceTest() {try {Session mysqlSession = mysqlSessionFactory.openSession();// 獲得數(shù)據(jù)庫元數(shù)據(jù)DatabaseMetaData meatData = mysqlSession.connection().getMetaData();// 默認(rèn)啟動數(shù)據(jù)源 dataSource1//斷言當(dāng)前數(shù)據(jù)源URL是否是dataSource1的URL assertEquals(dataSource1_URL, meatData.getURL());// 切換到數(shù)據(jù)源 dataSource2 ContextHolder.setDbType(DBType.dataSource2);mysqlSession = mysqlSessionFactory.openSession();meatData = mysqlSession.connection().getMetaData();//斷言當(dāng)前數(shù)據(jù)源URL是否是dataSource2的URL assertEquals(dataSource2_URL, meatData.getURL());} catch (Exception e) {e.printStackTrace();}}@SuppressWarnings("deprecation")@Testpublic void accessDataSourceTest() {try {Session accessSession = aceessSessionFactory.openSession();// 獲得數(shù)據(jù)庫元數(shù)據(jù)DatabaseMetaData meatData = accessSession.connection().getMetaData();//斷言當(dāng)前數(shù)據(jù)源URL是否是dataSource3的URL assertEquals(dataSource3_URL, meatData.getURL());} catch (Exception e) {e.printStackTrace();}}} 7.測試結(jié)果

轉(zhuǎn)載于:https://www.cnblogs.com/lowerCaseK/archive/2013/04/18/ChangeDataSource.html

總結(jié)

以上是生活随笔為你收集整理的动态切换数据源(spring+hibernate)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。