Spring+Hibernate实现动态SessionFactory切换
场景:
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切换的更多相关文章
- Spring+Hibernate实现动态SessionFactory切换(改进版)
前面写了一篇关于动态切换Hibernate SessionFactory的文章 发现存在一些问题: 需要配置多个HibernateTransactionManager和多个Spring 切面 这样带来 ...
- Spring(AbstractRoutingDataSource)实现动态数据源切换--转载
原始出处:http://linhongyu.blog.51cto.com/6373370/1615895 一.前言 近期一项目A需实现数据同步到另一项目B数据库中,在不改变B项目的情况下,只好选择项目 ...
- Spring(AbstractRoutingDataSource)实现动态数据源切换
转自: http://blog.51cto.com/linhongyu/1615895 一.前言 近期一项目A需实现数据同步到另一项目B数据库中,在不改变B项目的情况下,只好选择项目A中切换数据源,直 ...
- spring hibernate实现动态替换表名(分表)
1.概述 其实最简单的办法就是使用原生sql,如 session.createSQLQuery("sql"),或者使用jdbcTemplate.但是项目中已经使用了hql的方式查询 ...
- dubbo服务+Spring事务+AOP动态数据源切换 出错
1:问题描述,以及分析 项目用了spring数据源动态切换,服务用的是dubbo.在运行一段时间后程序异常,更新操作没有切换到主库上. 这个问题在先调用读操作后再调用写操作会出现. 经日志分析原因: ...
- spring AbstractRoutingDataSource实现动态数据源切换
使用Spring 提供的 AbstractRoutingDataSource 实现 创建 AbstractRoutingDataSource 实现类,负责保存所有数据源与切换数据源策略:public ...
- Spring 实现动态数据源切换--转载 (AbstractRoutingDataSource)的使用
[参考]Spring(AbstractRoutingDataSource)实现动态数据源切换--转载 [参考] 利用Spring的AbstractRoutingDataSource解决多数据源的问题 ...
- 30个类手写Spring核心原理之动态数据源切换(8)
本文节选自<Spring 5核心原理> 阅读本文之前,请先阅读以下内容: 30个类手写Spring核心原理之自定义ORM(上)(6) 30个类手写Spring核心原理之自定义ORM(下)( ...
- Spring整合Hibernate 一 - 注入SessionFactory
Spring3 整合 Hibernate4 - 注入SessionFactory 版本: spring-framework-3.2.4.RELEASE hibernate-release-4.2.5. ...
随机推荐
- 如何使用 Telegram
Telegram是一款加密的实时通讯软件,本文告诉大家如何使用 这个软件. 在使用之前,需要保证自己已经开了梯子,如果没有梯子,那么就无法使用这个工具. 假如梯子是 127.0.0.1 端口 1080 ...
- 小白学习之Code First(五)
Fluent API:另一种配置实体类的方式,它比DataAnnorations提供了更多的配置 其中EntityTypeConfiguration这个类提供了重要的属性.方法来配置对应的实体类,可以 ...
- Oracle安装后遇到错误:The Network Adapter could not establish the connection
http://note.youdao.com/noteshare?id=e6baee7ea7b7f60d7a265124e2bdd46c&sub=988945C6DDE843D5A7D6588 ...
- 网络编程: 基于TCP协议的socket, 实现一对一, 一对多通信
TCP协议 面向连接 可靠的 面向字节流形式的 tcp是基于链接的,必须先启动服务端,然后再启动客户端去链接服务端 TCP协议编码流程: 服务器端: 客户端 实例化对 ...
- 使用AJAX实现分页
Fenye.html <!DOCTYPE html> <html> <head> <title>分页</title> </head&g ...
- 新电脑装不了win7?来试试我的方法!
好久没写日记了,今天稍有时间来写个有关于硬件的技术贴. 前段时间换了个惠普暗影精灵二代,它的cpu代数如图所示: 用了几天系统自带win10,不同浏览器字体模糊的问题是个问题,故而想装 ...
- animation3 背景小动画笔记
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- jquery刷新页面的实现代码(局部及全页面刷新)
局部刷新: 这个方法就多了去了,常见的有以下几种: $.get方法,$.post方法,$.getJson方法,$.ajax方法如下 前两种使用方法基本上一样 下面介绍全页面刷新方法:有时候可能会用到 ...
- springboot学习入门之五---开发Web应用之JSP篇
转载:http://tengj.top/2017/03/13/springboot5/ 1整体结构 整体的框架结构,跟前面介绍Thymeleaf的时候差不多,只是多了webapp这个用来存放jsp的目 ...
- leetCode Detect Capital
1.问题描述 Given a word, you need to judge whether the usage of capitals in it is right or not. We defin ...