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

相关文章

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

Java进阶13讲__第12讲_1/2

多线程、线程池 1.  线程概念 1.1  什么是线程 1.2  线程的好处 2.   创建线程的三种方式 注意事项 2.1  继承Thread类 2.1.1 认识  2.1.2  编码实现  package cn.hdc.oop10.Thread;import org.slf4j.Logger;import org.slf4j.LoggerFactory

JAVA智听未来一站式有声阅读平台听书系统小程序源码

智听未来,一站式有声阅读平台听书系统 🌟&nbsp;开篇:遇见未来,从“智听”开始 在这个快节奏的时代,你是否渴望在忙碌的间隙,找到一片属于自己的宁静角落?是否梦想着能随时随地,沉浸在知识的海洋,或是故事的奇幻世界里?今天,就让我带你一起探索“智听未来”——这一站式有声阅读平台听书系统,它正悄悄改变着我们的阅读方式,让未来触手可及! 📚&nbsp;第一站:海量资源,应有尽有 走进“智听

在cscode中通过maven创建java项目

在cscode中创建java项目 可以通过博客完成maven的导入 建立maven项目 使用快捷键 Ctrl + Shift + P 建立一个 Maven 项目 1 Ctrl + Shift + P 打开输入框2 输入 "> java create"3 选择 maven4 选择 No Archetype5 输入 域名6 输入项目名称7 建立一个文件目录存放项目,文件名一般为项目名8 确定