spring+hibernate多数据源切换のSessionFactory切换
2015-10-02 13:46
531 查看
看到好多多数据源的例子,有切换datasource的,有切换sessionFactory的,我的是mysql和sqlserver两个数据库之间的切换,涉及到方言,所以就采用了后者。因为之前差点成功了,但是由于疏忽犯了个脑残失误就卡在somewhe了 ,今天本来想理清一下思路问大神的,结果理了一下,自己搞定了。不废话了,直接进入正题。
首先说配置方面,正常情况下都是陪一个datasource,一个sessionfactory,有事务还要配置tansationManager,如果是多数据源的话,就会有两个datasource,如果是不同类型的数据库的话,就需要连个Sessionfactory来配置方言。以下是配置内容
好了,xml配置就这么多,然后开始用自己写的类来接管Sessionfactory和 TransationFactory。如上文中看到的
先写一个继承sessionfactory的接口DynamicSessionFactory
实现这个接口
事务管理类DynamicTransactionManager
最后写一个切换当前线程内容的类
OK 大功告成了`(*∩_∩*)′
首先说配置方面,正常情况下都是陪一个datasource,一个sessionfactory,有事务还要配置tansationManager,如果是多数据源的话,就会有两个datasource,如果是不同类型的数据库的话,就需要连个Sessionfactory来配置方言。以下是配置内容
<!-- mysql --> <bean id="dataSourceMS" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${datasource.driver}"/> <property name="jdbcUrl" value="${datasource.url}"/> <property name="user" value="${datasource.username}"/> <property name="password" value="${datasource.password}"/> <property name="acquireIncrement" value="${c3p0.acquireIncrement}"/> <property name="initialPoolSize" value="${c3p0.initialPoolSize}"/> <property name="minPoolSize" value="${c3p0.minPoolSize}"/> <property name="maxPoolSize" value="${c3p0.maxPoolSize}"/> <property name="maxIdleTime" value="${c3p0.maxIdleTime}"/> <property name="idleConnectionTestPeriod" value="${c3p0.idleConnectionTestPeriod}"/> <property name="maxStatements" value="${c3p0.maxStatements}"/> <property name="numHelperThreads" value="${c3p0.numHelperThreads}"/> <!-- <property name="preferredTestQuery" value="${c3p0.preferredTestQuery}"/> --> <property name="testConnectionOnCheckout" value="${c3p0.testConnectionOnCheckout}"/> </bean> <bean id="sessionFactoryMS" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSourceMS" /> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </prop> <prop key="hibernate.show_sql">false</prop> <prop key="hibernate.cache.region.factory_class"> org.hibernate.cache.ehcache.EhCacheRegionFactory </prop> <prop key="hibernate.format_sql">false</prop> <prop key="hibernate.use_sql_comments">false</prop> <prop key="hibernate.jdbc.fetch_size">80</prop> <prop key="hibernate.jdbc.batch_size">80</prop> <prop key="hibernate.jdbc.use_streams_for_binary"> true </prop> <prop key="hibernate.current_session_context_class"> org.springframework.orm.hibernate4.SpringSessionContext </prop> <prop key="hibernate.cache.use_second_level_cache"> true </prop> <prop key="hibernate.cache.use_query_cache">true</prop> <prop key="hibernate.max_fetch_depth">3</prop> <prop key="hibernate.hbm2ddl.auto">none</prop> </props> </property> <property name="packagesToScan" value="com.ivo.*" /> </bean> <!-- sqlServer --> <bean id="dataSourceSS" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${datasource2.driver}"/> <property name="jdbcUrl" value="${datasource2.url}"/> <property name="user" value="${datasource2.username}"/> <property name="password" value="${datasource2.password}"/> <property name="acquireIncrement" value="${c3p0.acquireIncrement}"/> <property name="initialPoolSize" value="${c3p0.initialPoolSize}"/> <property name="minPoolSize" value="${c3p0.minPoolSize}"/> <property name="maxPoolSize" value="${c3p0.maxPoolSize}"/> <property name="maxIdleTime" value="${c3p0.maxIdleTime}"/> <property name="idleConnectionTestPeriod" value="${c3p0.idleConnectionTestPeriod}"/> <property name="maxStatements" value="${c3p0.maxStatements}"/> <property name="numHelperThreads" value="${c3p0.numHelperThreads}"/> <!-- <property name="preferredTestQuery" value="${c3p0.preferredTestQuery}"/> --> <property name="testConnectionOnCheckout" value="${c3p0.testConnectionOnCheckout}"/> </bean> <bean id="sessionFactorySS" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSourceSS" /> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.SQLServerDialect </prop> <prop key="hibernate.show_sql">false</prop> <prop key="hibernate.cache.region.factory_class"> org.hibernate.cache.ehcache.EhCacheRegionFactory </prop> <prop key="hibernate.format_sql">false</prop> <prop key="hibernate.use_sql_comments">false</prop> <prop key="hibernate.jdbc.fetch_size">80</prop> <prop key="hibernate.jdbc.batch_size">80</prop> <prop key="hibernate.jdbc.use_streams_for_binary"> true </prop> <prop key="hibernate.current_session_context_class"> org.springframework.orm.hibernate4.SpringSessionContext </prop> <prop key="hibernate.cache.use_second_level_cache"> true </prop> <prop key="hibernate.cache.use_query_cache">true</prop> <prop key="hibernate.max_fetch_depth">3</prop> <prop key="hibernate.hbm2ddl.auto">none</prop> </props> </property> <property name="packagesToScan" value="com.ivo.*" /> </bean> <!-- 动态SessionFactory --> <bean id="sessionFactory" class="com.ivo.util2.DynamicSessionFactoryImpl"> <property name="defaultTargetSessionFactory" ref="sessionFactoryMS"/> <property name="targetSessionFactorys"> <map> <entry value-ref="sessionFactoryMS" key="sessionFactoryMS"/> <entry value-ref="sessionFactorySS" key="sessionFactorySS"/> </map> </property> </bean> <bean class="com.ivo.core.HibernateInvoker"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 自定义动态切换SessionFactory事务管理器,注入sessionFactory --> <bean id="transactionManager" class="com.ivo.util2.DynamicTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean>
好了,xml配置就这么多,然后开始用自己写的类来接管Sessionfactory和 TransationFactory。如上文中看到的
com.ivo.util2.DynamicSessionFactoryImpl 和 <span style="font-family: Arial, Helvetica, sans-serif;">com.ivo.util2.DynamicTransactionManager</span>
先写一个继承sessionfactory的接口DynamicSessionFactory
package com.ivo.util2; import org.hibernate.SessionFactory; public interface DynamicSessionFactory extends SessionFactory { public SessionFactory getHibernateSessionFactory(); }
实现这个接口
DynamicSessionFactoryImpl
package com.ivo.util2; import com.ivo.util.CustomerContextHolder; import com.ivo.util2.DynamicSessionFactory; import java.io.Serializable; import java.sql.Connection; import java.util.Map; import java.util.Set; import javax.naming.NamingException; import javax.naming.Reference; import org.hibernate.Cache; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionBuilder; import org.hibernate.SessionFactory; import org.hibernate.StatelessSession; import org.hibernate.StatelessSessionBuilder; import org.hibernate.TypeHelper; import org.hibernate.engine.spi.FilterDefinition; import org.hibernate.metadata.ClassMetadata; import org.hibernate.metadata.CollectionMetadata; import org.hibernate.stat.Statistics; public class DynamicSessionFactoryImpl implements DynamicSessionFactory { /** * */ private static final long serialVersionUID = 7328134180626920452L; private Map<Object, SessionFactory> targetSessionFactorys; private SessionFactory defaultTargetSessionFactory; @Override public SessionFactoryOptions getSessionFactoryOptions() { return getHibernateSessionFactory().getSessionFactoryOptions(); } @Override public SessionBuilder withOptions() { return getHibernateSessionFactory().withOptions(); } @Override public Session openSession() throws HibernateException { return getHibernateSessionFactory().openSession(); } @Override public Session getCurrentSession() throws HibernateException { return getHibernateSessionFactory().getCurrentSession(); } @Override public StatelessSessionBuilder withStatelessOptions() { return getHibernateSessionFactory().withStatelessOptions(); } @Override public StatelessSession openStatelessSession() { return getHibernateSessionFactory().openStatelessSession(); } @Override public StatelessSession openStatelessSession(Connection connection) { return getHibernateSessionFactory().openStatelessSession(connection); } @Override public ClassMetadata getClassMetadata( @SuppressWarnings("rawtypes") Class entityClass) { return getHibernateSessionFactory().getClassMetadata(entityClass); } @Override public ClassMetadata getClassMetadata(String entityName) { return getHibernateSessionFactory().getClassMetadata(entityName); } @Override public CollectionMetadata getCollectionMetadata(String roleName) { return getHibernateSessionFactory().getCollectionMetadata(roleName); } @Override public Map<String, ClassMetadata> getAllClassMetadata() { return getHibernateSessionFactory().getAllClassMetadata(); } @SuppressWarnings("rawtypes") @Override public Map getAllCollectionMetadata() { return getHibernateSessionFactory().getAllCollectionMetadata(); } @Override public Statistics getStatistics() { return getHibernateSessionFactory().getStatistics(); } @Override public void close() throws HibernateException { getHibernateSessionFactory().close(); } @Override public boolean isClosed() { return getHibernateSessionFactory().isClosed(); } @Override public Cache getCache() { return getHibernateSessionFactory().getCache(); } @SuppressWarnings({ "deprecation", "rawtypes" }) @Override public void evict(Class persistentClass) throws HibernateException { getHibernateSessionFactory().evict(persistentClass); } @SuppressWarnings({ "deprecation", "rawtypes" }) @Override public void evict(Class persistentClass, Serializable id) throws HibernateException { getHibernateSessionFactory().evict(persistentClass, id); } @SuppressWarnings("deprecation") @Override public void evictEntity(String entityName) throws HibernateException { getHibernateSessionFactory().evictEntity(entityName); } @SuppressWarnings("deprecation") @Override public void evictEntity(String entityName, Serializable id) throws HibernateException { getHibernateSessionFactory().evictEntity(entityName, id); } @SuppressWarnings("deprecation") @Override public void evictCollection(String roleName) throws HibernateException { getHibernateSessionFactory().evictCollection(roleName); } @SuppressWarnings("deprecation") @Override public void evictCollection(String roleName, Serializable id) throws HibernateException { getHibernateSessionFactory().evictCollection(roleName, id); } @SuppressWarnings("deprecation") @Override public void evictQueries(String cacheRegion) throws HibernateException { getHibernateSessionFactory().evictQueries(cacheRegion); } @SuppressWarnings("deprecation") @Override public void evictQueries() throws HibernateException { getHibernateSessionFactory().evictQueries(); } @SuppressWarnings("rawtypes") @Override public Set getDefinedFilterNames() { return getHibernateSessionFactory().getDefinedFilterNames(); } @Override public FilterDefinition getFilterDefinition(String filterName) throws HibernateException { return getHibernateSessionFactory().getFilterDefinition(filterName); } @Override public boolean containsFetchProfileDefinition(String name) { return getHibernateSessionFactory() .containsFetchProfileDefinition(name); } @Override public TypeHelper getTypeHelper() { return getHibernateSessionFactory().getTypeHelper(); } @Override public Reference getReference() throws NamingException { return getHibernateSessionFactory().getReference(); } @Override public SessionFactory getHibernateSessionFactory() { SessionFactory targetSessionFactory = targetSessionFactorys .get(CustomerContextHolder.getCustomerType()); if (targetSessionFactory != null) { return targetSessionFactory; } else if (defaultTargetSessionFactory != null) { return defaultTargetSessionFactory; } return null; } public void setTargetSessionFactorys( Map<Object, SessionFactory> targetSessionFactorys) { this.targetSessionFactorys = targetSessionFactorys; } public void setDefaultTargetSessionFactory( SessionFactory defaultTargetSessionFactory) { this.defaultTargetSessionFactory = defaultTargetSessionFactory; } }
事务管理类DynamicTransactionManager
package com.ivo.util2; import org.springframework.orm.hibernate4.HibernateTransactionManager; import javax.sql.DataSource; import org.hibernate.SessionFactory; import org.springframework.orm.hibernate4.SessionFactoryUtils; public class DynamicTransactionManager extends HibernateTransactionManager { /** * */ private static final long serialVersionUID = 2591641126163504954L; @Override public DataSource getDataSource() { return SessionFactoryUtils.getDataSource(getSessionFactory()); } @Override public SessionFactory getSessionFactory() { DynamicSessionFactory dynamicSessionFactory = (DynamicSessionFactory) super.getSessionFactory(); SessionFactory hibernateSessionFactory = dynamicSessionFactory.getHibernateSessionFactory(); return hibernateSessionFactory; } }
最后写一个切换当前线程内容的类
package com.ivo.util2; public class CustomerContextHolder { public static final String SESSION_FACTORY_MYSQL = "sessionFactoryMS"; public static final String SESSION_FACTORY_SQLSERVER = "sessionFactorySS"; private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>(); public static void setCustomerType(String dbType) { contextHolder.set(dbType); } public static String getCustomerType() { return contextHolder.get(); } public static void clearCustomerType() { contextHolder.remove(); } }
OK 大功告成了`(*∩_∩*)′
相关文章推荐
- SpringMVC学习指南<二> 模型2和MVC模式
- spring框架
- NotePad++中的GBK乱码问题
- Java WebService
- Java并发编程专题
- java 类加载器
- spring 配置中,数据库相关信息如何加密放在属性文件中
- Java中instanceof关键字用法
- Java身份证号码数据验证
- 基于Xpath的简单的学生信息管理系统
- java rmi两种实现
- java.lang.OutOfMemoryError: Java heap space
- java7 MethodHandle学习笔记
- Java中普通代码块,构造代码块,静态代码块区别及代码示例
- JAVA 基础加密算法
- Ubuntu14.04+OpenJDK7下载编译安卓源代码
- java制作视频播放器
- Debug---Eclipse断点调试基础
- 三大框架学习之----struts2 通配符的使用(二)
- How many Fibs?(java)