本文主要是介绍spring+hibernate多数据源切换のSessionFactory切换,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
看到好多多数据源的例子,有切换datasource的,有切换sessionFactory的,我的是mysql和sqlserver两个数据库之间的切换,涉及到方言,所以就采用了后者。因为之前差点成功了,但是由于疏忽犯了个脑残失误就卡在somewhe了 ,今天本来想理清一下思路问大神的,结果理了一下,自己搞定了。不废话了,直接进入正题。
首先说配置方面,正常情况下都是陪一个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;@Overridepublic SessionFactoryOptions getSessionFactoryOptions() {return getHibernateSessionFactory().getSessionFactoryOptions();}@Overridepublic SessionBuilder withOptions() {return getHibernateSessionFactory().withOptions();}@Overridepublic Session openSession() throws HibernateException {return getHibernateSessionFactory().openSession();}@Overridepublic Session getCurrentSession() throws HibernateException {return getHibernateSessionFactory().getCurrentSession();}@Overridepublic StatelessSessionBuilder withStatelessOptions() {return getHibernateSessionFactory().withStatelessOptions();}@Overridepublic StatelessSession openStatelessSession() {return getHibernateSessionFactory().openStatelessSession();}@Overridepublic StatelessSession openStatelessSession(Connection connection) {return getHibernateSessionFactory().openStatelessSession(connection);}@Overridepublic ClassMetadata getClassMetadata(@SuppressWarnings("rawtypes") Class entityClass) {return getHibernateSessionFactory().getClassMetadata(entityClass);}@Overridepublic ClassMetadata getClassMetadata(String entityName) {return getHibernateSessionFactory().getClassMetadata(entityName);}@Overridepublic CollectionMetadata getCollectionMetadata(String roleName) {return getHibernateSessionFactory().getCollectionMetadata(roleName);}@Overridepublic Map<String, ClassMetadata> getAllClassMetadata() {return getHibernateSessionFactory().getAllClassMetadata();}@SuppressWarnings("rawtypes")@Overridepublic Map getAllCollectionMetadata() {return getHibernateSessionFactory().getAllCollectionMetadata();}@Overridepublic Statistics getStatistics() {return getHibernateSessionFactory().getStatistics();}@Overridepublic void close() throws HibernateException {getHibernateSessionFactory().close();}@Overridepublic boolean isClosed() {return getHibernateSessionFactory().isClosed();}@Overridepublic Cache getCache() {return getHibernateSessionFactory().getCache();}@SuppressWarnings({ "deprecation", "rawtypes" })@Overridepublic void evict(Class persistentClass) throws HibernateException {getHibernateSessionFactory().evict(persistentClass);}@SuppressWarnings({ "deprecation", "rawtypes" })@Overridepublic void evict(Class persistentClass, Serializable id)throws HibernateException {getHibernateSessionFactory().evict(persistentClass, id);}@SuppressWarnings("deprecation")@Overridepublic void evictEntity(String entityName) throws HibernateException {getHibernateSessionFactory().evictEntity(entityName);}@SuppressWarnings("deprecation")@Overridepublic void evictEntity(String entityName, Serializable id)throws HibernateException {getHibernateSessionFactory().evictEntity(entityName, id);}@SuppressWarnings("deprecation")@Overridepublic void evictCollection(String roleName) throws HibernateException {getHibernateSessionFactory().evictCollection(roleName);}@SuppressWarnings("deprecation")@Overridepublic void evictCollection(String roleName, Serializable id)throws HibernateException {getHibernateSessionFactory().evictCollection(roleName, id);}@SuppressWarnings("deprecation")@Overridepublic void evictQueries(String cacheRegion) throws HibernateException {getHibernateSessionFactory().evictQueries(cacheRegion);}@SuppressWarnings("deprecation")@Overridepublic void evictQueries() throws HibernateException {getHibernateSessionFactory().evictQueries();}@SuppressWarnings("rawtypes")@Overridepublic Set getDefinedFilterNames() {return getHibernateSessionFactory().getDefinedFilterNames();}@Overridepublic FilterDefinition getFilterDefinition(String filterName)throws HibernateException {return getHibernateSessionFactory().getFilterDefinition(filterName);}@Overridepublic boolean containsFetchProfileDefinition(String name) {return getHibernateSessionFactory().containsFetchProfileDefinition(name);}@Overridepublic TypeHelper getTypeHelper() {return getHibernateSessionFactory().getTypeHelper();}@Overridepublic Reference getReference() throws NamingException {return getHibernateSessionFactory().getReference();}@Overridepublic 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;}
}
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;@Overridepublic DataSource getDataSource() {return SessionFactoryUtils.getDataSource(getSessionFactory());}@Overridepublic 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 大功告成了`(*∩_∩*)′
这篇关于spring+hibernate多数据源切换のSessionFactory切换的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!