场景:

1)系统有多个数据库

2)且数据库类型也不尽相同

3)现在应用根据某些条件路由到具体的数据库

4)且在spring+hibernate框架下,支持依赖注入

已有实现,spring动态数据源,但无法实现动态SessionFactory,即不通数据库的方言不一样

目标:

在spring动态数据源的基础上,实现动态SessionFactory

1.配置多个数据源和SessionFactory,并给相应SessionFactory配置事务管理:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- FOR SqlServer-->
<bean id="SqlServer_DataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="url"
value="url" />
<property name="username" value="username" />
<property name="password" value="password" />
</bean>
<bean id="SqlServer_SessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"
p:mappingLocations="classpath:/com/entity/*.hbm.xml">
<property name="dataSource" ref="SqlServer_DataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.query.factory_class">org.hibernate.hql.ast.ASTQueryTranslatorFactory</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServer2008Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
<bean id="SqlServer_TransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="SqlServer_SessionFactory"/>
</bean> <!-- FOR Oracle -->
<bean id="Oracle _DataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521/orcl" />
<property name="username" value="username" />
<property name="password" value="password" />
</bean>
<bean id="Oracle_SessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"
p:mappingLocations="classpath:/com/entity/*.hbm.xml">
<property name="dataSource" ref="Oracle_DataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.query.factory_class">org.hibernate.hql.ast.ASTQueryTranslatorFactory</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
<bean id="Oracle_TransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="Oracle_SessionFactory"/>
</bean> </beans>

2. 为SessionFactory配置事务切面:

<tx:advice id="SqlServer_TxAdvice" transaction-manager="SqlServer_TransactionManager">
<tx:attributes>
<tx:method name="get*" read-only="true" />
<tx:method name="find*" read-only="true" />
<tx:method name="*" propagation="REQUIRED" rollback-for="Exception" />
</tx:attributes>
</tx:advice>
<tx:advice id="Oracle_TxAdvice" transaction-manager="Oracle_TransactionManager">
<tx:attributes>
<tx:method name="get*" read-only="true" />
<tx:method name="find*" read-only="true" />
<tx:method name="*" propagation="REQUIRED" rollback-for="Exception" />
</tx:attributes>
</tx:advice> <aop:config proxy-target-class="true">
<aop:pointcut id="txPointcut" expression="execution(* com.service.*.*(..))"/>
<aop:advisor advice-ref="SqlServer_TxAdvice" pointcut-ref="txPointcut" order="1"/>
<aop:advisor advice-ref="Oracle_TxAdvice" pointcut-ref="txPointcut" order="2"/>
</aop:config>

3. 配置一个动态的SessionFactory:

<bean id="sessionFactory" class="com.DynamicSessionFactory"/>

4. 定义DynamicSessionFactory实现接口SessionFactory:

public class DynamicSessionFactory implements SessionFactory ,ApplicationContextAware{

    private static final long serialVersionUID = 1L;

    private ApplicationContext applicationContext;

    private SessionFactory getSessionFactory(String name) {
return (SessionFactory) applicationContext.getBean(name);
}
//根据当前线程的SessionFactoryName获取SessionFactory
private SessionFactory getSessionFactory() {
return getSessionFactory(ThreadLocalUtil.
.getSessionFactoryName());
} public Reference getReference() throws NamingException {
return getSessionFactory().getReference();
} public Session openSession() throws HibernateException {
return getSessionFactory().openSession();
} public Session openSession(Interceptor interceptor)
throws HibernateException {
return getSessionFactory().openSession(interceptor);
} public Session openSession(Connection connection) {
return getSessionFactory().openSession(connection);
} public Session openSession(Connection connection, Interceptor interceptor) {
return getSessionFactory().openSession(connection,interceptor);
} public Session getCurrentSession() throws HibernateException {
return getSessionFactory().getCurrentSession();
} public StatelessSession openStatelessSession() {
return getSessionFactory().openStatelessSession();
} public StatelessSession openStatelessSession(Connection connection) {
return getSessionFactory().openStatelessSession(connection);
} public ClassMetadata getClassMetadata(Class entityClass) {
return getSessionFactory().getClassMetadata(entityClass);
} public ClassMetadata getClassMetadata(String entityName) {
return getSessionFactory().getClassMetadata(entityName);
} public CollectionMetadata getCollectionMetadata(String roleName) {
return getSessionFactory().getCollectionMetadata(roleName);
} public Map getAllClassMetadata() {
return getSessionFactory().getAllClassMetadata();
} public Map getAllCollectionMetadata() {
return getSessionFactory().getAllCollectionMetadata();
} public Statistics getStatistics() {
return getSessionFactory().getStatistics();
} public void close() throws HibernateException {
getSessionFactory().close();
} public boolean isClosed() {
return getSessionFactory().isClosed();
} public Cache getCache() {
return getSessionFactory().getCache();
} public void evict(Class persistentClass) throws HibernateException {
getSessionFactory().evict(persistentClass);
} public void evict(Class persistentClass, Serializable id)
throws HibernateException {
getSessionFactory().evict(persistentClass, id);
} public void evictEntity(String entityName) throws HibernateException {
getSessionFactory().evictEntity(entityName);
} public void evictEntity(String entityName, Serializable id)
throws HibernateException {
getSessionFactory().evictEntity(entityName, id);
} public void evictCollection(String roleName) throws HibernateException {
getSessionFactory().evictCollection(roleName);
} public void evictCollection(String roleName, Serializable id)
throws HibernateException {
getSessionFactory().evictCollection(roleName, id);
} public void evictQueries(String cacheRegion) throws HibernateException {
getSessionFactory().evictQueries(cacheRegion);
} public void evictQueries() throws HibernateException {
getSessionFactory().evictQueries();
} public Set getDefinedFilterNames() {
return getSessionFactory().getDefinedFilterNames();
} public FilterDefinition getFilterDefinition(String filterName)
throws HibernateException {
return getSessionFactory().getFilterDefinition(filterName);
} public boolean containsFetchProfileDefinition(String name) {
return getSessionFactory().containsFetchProfileDefinition(name);
} @Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.applicationContext = applicationContext;
} }

Spring+Hibernate实现动态SessionFactory切换的更多相关文章

  1. Spring+Hibernate实现动态SessionFactory切换(改进版)

    前面写了一篇关于动态切换Hibernate SessionFactory的文章 发现存在一些问题: 需要配置多个HibernateTransactionManager和多个Spring 切面 这样带来 ...

  2. Spring(AbstractRoutingDataSource)实现动态数据源切换--转载

    原始出处:http://linhongyu.blog.51cto.com/6373370/1615895 一.前言 近期一项目A需实现数据同步到另一项目B数据库中,在不改变B项目的情况下,只好选择项目 ...

  3. Spring(AbstractRoutingDataSource)实现动态数据源切换

    转自: http://blog.51cto.com/linhongyu/1615895 一.前言 近期一项目A需实现数据同步到另一项目B数据库中,在不改变B项目的情况下,只好选择项目A中切换数据源,直 ...

  4. spring hibernate实现动态替换表名(分表)

    1.概述 其实最简单的办法就是使用原生sql,如 session.createSQLQuery("sql"),或者使用jdbcTemplate.但是项目中已经使用了hql的方式查询 ...

  5. dubbo服务+Spring事务+AOP动态数据源切换 出错

    1:问题描述,以及分析 项目用了spring数据源动态切换,服务用的是dubbo.在运行一段时间后程序异常,更新操作没有切换到主库上. 这个问题在先调用读操作后再调用写操作会出现. 经日志分析原因: ...

  6. spring AbstractRoutingDataSource实现动态数据源切换

    使用Spring 提供的 AbstractRoutingDataSource 实现 创建 AbstractRoutingDataSource 实现类,负责保存所有数据源与切换数据源策略:public ...

  7. Spring 实现动态数据源切换--转载 (AbstractRoutingDataSource)的使用

    [参考]Spring(AbstractRoutingDataSource)实现动态数据源切换--转载 [参考] 利用Spring的AbstractRoutingDataSource解决多数据源的问题 ...

  8. 30个类手写Spring核心原理之动态数据源切换(8)

    本文节选自<Spring 5核心原理> 阅读本文之前,请先阅读以下内容: 30个类手写Spring核心原理之自定义ORM(上)(6) 30个类手写Spring核心原理之自定义ORM(下)( ...

  9. Spring整合Hibernate 一 - 注入SessionFactory

    Spring3 整合 Hibernate4 - 注入SessionFactory 版本: spring-framework-3.2.4.RELEASE hibernate-release-4.2.5. ...

随机推荐

  1. sqlserver中利用Tran_sql把逗号分隔的字符串拆成临时表

    在与数据库交互的过程中,我们经常需要把一串ID组成的字符串当作参数传给存储过程获取数据.很多时候我们希望把这个字符串转成集合以方便用于in操作. 有两种方式可以方便地把这个以某种符号分隔的ID字符串转 ...

  2. 阿里云提示ECS服务器存在漏洞处理方法

    1.阿里云提供生成修复命令,但是这个只提供给企业版,即收费的: 2.自己手动修复的话, 采用软件升级一般都可以解决.除了提示带kernel的高危漏洞的,其他的不需要重启实例即可修复. 有kernel的 ...

  3. javascript正则表达式获取控制

    正则表达式的元字符是包含特殊含义的字符,他们有一些特殊的功能,可以控制匹配模式的方式,反斜杠后的元字符将失去其特殊含义 单个字符 元字符 匹配情况 . 匹配除换行符外的任意字符 [a-z0-9] 匹配 ...

  4. hdu 1043 八数码问题

    Eight Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Subm ...

  5. 一步一步实现web程序信息管理系统之一----登陆界面实现

    一步一步实现web程序信息管理系统 在web程序中特别是信息管理系统,登陆功能必须有而且特别重要.每一个学习程序开发或以后工作中,都会遇到实现登陆功能的需求.而登陆功能最终提供给客户或展现给客户的最基 ...

  6. 记ASP.NET 使用 X509Certificate2 出现的一系列问题

    在做微信支付退款的时候,由于需要使用到p12证书,结果就遇到一系列的坑.这里做个记录方便以后查阅. 原先加载证书的代码: X509Certificate2 cert = new X509Certifi ...

  7. Postman Postman接口测试工具使用简介

    Postman接口测试工具使用简介 by:授客 QQ:1033553122 本文主要是对Postman这个接口测试工具的使用做个简单的介绍,仅供参考. 插件安装 1)下载并安装chrome浏览器 2) ...

  8. Progress数据库配置与应用

    创建database 开始->程序->OpenEdge,选择:Desktop,进行database创建. 选择创建一个空database或直接copy一个demo的database,我们选 ...

  9. android 每个块半径不同的扇形图,自定义view

    1.首先看效果图 2.自定义PieChartView,继承自View,下边为PieChartView代码 package com.yingjinbao.im.peach.customview; imp ...

  10. Pig group用法举例

        group语句可以把具有相同键值的数据聚合在一起,与SQL中的group操作有着本质的区别,在SQL中group by字句创建的组必须直接注入一个或多个聚合函数.在Pig Latin中grou ...