spring+hibernate多数据源切换のSessionFactory切换

2024-06-01 08:38

本文主要是介绍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;}
}


事务管理类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;@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切换的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1020516

相关文章

Java编译生成多个.class文件的原理和作用

《Java编译生成多个.class文件的原理和作用》作为一名经验丰富的开发者,在Java项目中执行编译后,可能会发现一个.java源文件有时会产生多个.class文件,从技术实现层面详细剖析这一现象... 目录一、内部类机制与.class文件生成成员内部类(常规内部类)局部内部类(方法内部类)匿名内部类二、

SpringBoot实现数据库读写分离的3种方法小结

《SpringBoot实现数据库读写分离的3种方法小结》为了提高系统的读写性能和可用性,读写分离是一种经典的数据库架构模式,在SpringBoot应用中,有多种方式可以实现数据库读写分离,本文将介绍三... 目录一、数据库读写分离概述二、方案一:基于AbstractRoutingDataSource实现动态

Springboot @Autowired和@Resource的区别解析

《Springboot@Autowired和@Resource的区别解析》@Resource是JDK提供的注解,只是Spring在实现上提供了这个注解的功能支持,本文给大家介绍Springboot@... 目录【一】定义【1】@Autowired【2】@Resource【二】区别【1】包含的属性不同【2】@

springboot循环依赖问题案例代码及解决办法

《springboot循环依赖问题案例代码及解决办法》在SpringBoot中,如果两个或多个Bean之间存在循环依赖(即BeanA依赖BeanB,而BeanB又依赖BeanA),会导致Spring的... 目录1. 什么是循环依赖?2. 循环依赖的场景案例3. 解决循环依赖的常见方法方法 1:使用 @La

Java枚举类实现Key-Value映射的多种实现方式

《Java枚举类实现Key-Value映射的多种实现方式》在Java开发中,枚举(Enum)是一种特殊的类,本文将详细介绍Java枚举类实现key-value映射的多种方式,有需要的小伙伴可以根据需要... 目录前言一、基础实现方式1.1 为枚举添加属性和构造方法二、http://www.cppcns.co

Elasticsearch 在 Java 中的使用教程

《Elasticsearch在Java中的使用教程》Elasticsearch是一个分布式搜索和分析引擎,基于ApacheLucene构建,能够实现实时数据的存储、搜索、和分析,它广泛应用于全文... 目录1. Elasticsearch 简介2. 环境准备2.1 安装 Elasticsearch2.2 J

Java中的String.valueOf()和toString()方法区别小结

《Java中的String.valueOf()和toString()方法区别小结》字符串操作是开发者日常编程任务中不可或缺的一部分,转换为字符串是一种常见需求,其中最常见的就是String.value... 目录String.valueOf()方法方法定义方法实现使用示例使用场景toString()方法方法

Java中List的contains()方法的使用小结

《Java中List的contains()方法的使用小结》List的contains()方法用于检查列表中是否包含指定的元素,借助equals()方法进行判断,下面就来介绍Java中List的c... 目录详细展开1. 方法签名2. 工作原理3. 使用示例4. 注意事项总结结论:List 的 contain

Java实现文件图片的预览和下载功能

《Java实现文件图片的预览和下载功能》这篇文章主要为大家详细介绍了如何使用Java实现文件图片的预览和下载功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... Java实现文件(图片)的预览和下载 @ApiOperation("访问文件") @GetMapping("

Spring Boot + MyBatis Plus 高效开发实战从入门到进阶优化(推荐)

《SpringBoot+MyBatisPlus高效开发实战从入门到进阶优化(推荐)》本文将详细介绍SpringBoot+MyBatisPlus的完整开发流程,并深入剖析分页查询、批量操作、动... 目录Spring Boot + MyBATis Plus 高效开发实战:从入门到进阶优化1. MyBatis