Spring+Hibernate实现动态SessionFactory切换(改进版)
前面写了一篇关于动态切换Hibernate SessionFactory的文章
发现存在一些问题:
需要配置多个HibernateTransactionManager和多个Spring 切面
这样带来两个问题
1. 程序效率降低,因为Spring进行多次Advice的拦截
2. 如果其中一个SessionFactory连接出现问题,会导致整个系统无法工作
今天研究出一种新的方法来解决此类问题
1. 数据源及Hibernate 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> <!-- 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> </beans>
2. 定义扩展接口DynamicSessionFactoryInf继承SessionFactory
import org.hibernate.SessionFactory;
public interface DynamicSessionFactoryInf extends SessionFactory {
public SessionFactory getHibernateSessionFactory();
}
3. 定义DynamicSessionFactory实现DynamicSessionFactoryInf
public class DynamicSessionFactory implements DynamicSessionFactoryInf ,ApplicationContextAware{
private static final long serialVersionUID = 1L;
private ApplicationContext applicationContext;
//动态调用SessionFactory
private SessionFactory getHibernateSessionFactory(String name) {
return (SessionFactory) applicationContext.getBean(name);
}
//实现DynamicSessionFactoryInf 接口的方法
public SessionFactory getHibernateSessionFactory() {
return getHibernateSessionFactory(ThreadLocalUtil.getCurrentITAsset()
.getSessionFactoryName());
}
//以下是实现SessionFactory接口的方法,并对当前的SessionFactory实体进行代理
public Reference getReference() throws NamingException {
return getHibernateSessionFactory().getReference();
}
public Session openSession() throws HibernateException {
return getHibernateSessionFactory().openSession();
}
public Session openSession(Interceptor interceptor)
throws HibernateException {
return getHibernateSessionFactory().openSession(interceptor);
}
public Session openSession(Connection connection) {
return getHibernateSessionFactory().openSession(connection);
}
public Session openSession(Connection connection, Interceptor interceptor) {
return getHibernateSessionFactory().openSession(connection,interceptor);
}
public Session getCurrentSession() throws HibernateException {
return getHibernateSessionFactory().getCurrentSession();
}
public StatelessSession openStatelessSession() {
return getHibernateSessionFactory().openStatelessSession();
}
public StatelessSession openStatelessSession(Connection connection) {
return getHibernateSessionFactory().openStatelessSession(connection);
}
public ClassMetadata getClassMetadata(Class entityClass) {
return getHibernateSessionFactory().getClassMetadata(entityClass);
}
public ClassMetadata getClassMetadata(String entityName) {
return getHibernateSessionFactory().getClassMetadata(entityName);
}
public CollectionMetadata getCollectionMetadata(String roleName) {
return getHibernateSessionFactory().getCollectionMetadata(roleName);
}
public Map getAllClassMetadata() {
return getHibernateSessionFactory().getAllClassMetadata();
}
public Map getAllCollectionMetadata() {
return getHibernateSessionFactory().getAllCollectionMetadata();
}
public Statistics getStatistics() {
return getHibernateSessionFactory().getStatistics();
}
public void close() throws HibernateException {
getHibernateSessionFactory().close();
}
public boolean isClosed() {
return getHibernateSessionFactory().isClosed();
}
public Cache getCache() {
return getHibernateSessionFactory().getCache();
}
public void evict(Class persistentClass) throws HibernateException {
getHibernateSessionFactory().evict(persistentClass);
}
public void evict(Class persistentClass, Serializable id)
throws HibernateException {
getHibernateSessionFactory().evict(persistentClass, id);
}
public void evictEntity(String entityName) throws HibernateException {
getHibernateSessionFactory().evictEntity(entityName);
}
public void evictEntity(String entityName, Serializable id)
throws HibernateException {
getHibernateSessionFactory().evictEntity(entityName, id);
}
public void evictCollection(String roleName) throws HibernateException {
getHibernateSessionFactory().evictCollection(roleName);
}
public void evictCollection(String roleName, Serializable id)
throws HibernateException {
getHibernateSessionFactory().evictCollection(roleName, id);
}
public void evictQueries(String cacheRegion) throws HibernateException {
getHibernateSessionFactory().evictQueries(cacheRegion);
}
public void evictQueries() throws HibernateException {
getHibernateSessionFactory().evictQueries();
}
public Set getDefinedFilterNames() {
return getHibernateSessionFactory().getDefinedFilterNames();
}
public FilterDefinition getFilterDefinition(String filterName)
throws HibernateException {
return getHibernateSessionFactory().getFilterDefinition(filterName);
}
public boolean containsFetchProfileDefinition(String name) {
return getHibernateSessionFactory().containsFetchProfileDefinition(name);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.applicationContext = applicationContext;
}
}
4. 配置动态SessionFactory
<bean id="sessionFactory" class="com.hp.it.qdpadmin.common.DynamicSessionFactory"/>
5. 定义DynamicTransactionManager继承HibernateTransactionManager
public class DynamicTransactionManager extends HibernateTransactionManager {
private static final long serialVersionUID = 1047039346475978451L;
//重写getDataSource方法,实现动态获取
public DataSource getDataSource() {
DataSource sfds = SessionFactoryUtils.getDataSource(getSessionFactory());
return sfds;
}
//重写getSessionFactory方法,实现动态获取SessionFactory
public SessionFactory getSessionFactory() {
DynamicSessionFactoryInf dynamicSessionFactory = (DynamicSessionFactoryInf) super
.getSessionFactory();
SessionFactory hibernateSessionFactory = dynamicSessionFactory
.getHibernateSessionFactory();
return hibernateSessionFactory;
}
//重写afterPropertiesSet,跳过数据源的初始化等操作
public void afterPropertiesSet() {
return;
}
}
6. 配置dynamicTransactionManager
<bean id="dynamicTransactionManager"
class="com.hp.it.qdpadmin.common.DynamicTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
7. 为SessionFactory配置事务切面
<tx:advice id="dynamicTxAdvice" transaction-manager="dynamicTransactionManager">
<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="dynamicTxAdvice" pointcut-ref="txPointcut" />
</aop:config>
Spring+Hibernate实现动态SessionFactory切换(改进版)的更多相关文章
- Spring+Hibernate实现动态SessionFactory切换
场景: 1)系统有多个数据库 2)且数据库类型也不尽相同 3)现在应用根据某些条件路由到具体的数据库 4)且在spring+hibernate框架下,支持依赖注入 已有实现,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. ...
随机推荐
- GDB disassemble
前面几篇谈GDB调试程序的帖子,都对反汇编语焉不详.这里详细讨论一下disassemble/disass命令 反汇编一个函数disass func_name 反汇编一段内存地址, 第1个参数是起始地址 ...
- [物理学与PDEs]第3章第3节 电导率 $\sigma$ 为无穷时的磁流体力学方程组 3.3 磁场线``冻结''原理
磁场线``冻结''原理: 在 $\sigma=\infty$ 时, 初始时刻分布在同一磁场线上的质点, 在运动过程中会一直保持在同一磁场线上, 即磁场线好像``冻结''在物质上. 事实上, $\cfr ...
- [物理学与PDEs]第1章习题1 无限长直线的电场强度与电势
设有一均匀分布着电荷的无限长直线, 其上的电荷线密度 (即单位长度上的电荷量) 为 $\sigma$. 试求该直线所形成的电场的电场强度及电势. 解答: 设空间上点 $P$ 到直线的距离为 $r$, ...
- Vue Material
Material Design是什么? https://www.zhihu.com/topic/20005114/top-answers 我们挑战自我,为用户创造了崭新的视觉设计语言.与此同时,新的设 ...
- LESS知识总结
知识体系 1.认识less 2.使用less 3.变量( variables ) 4.混合 ( mixins ) 5.嵌套规则 ( nested-rules ) 6.运算(operation ...
- UML各种图总结-精华
UML(Unified Modeling Language)是一种统一建模语言,为面向对象开发系统的产品进行说明.可视化.和编制文档的一种标准语言.下面将对UML的九种图+包图的基本概念进行介绍以及各 ...
- TCP-IP详解笔记7
TCP-IP详解笔记7 TCP: 传输控制协议(初步) 使用差错校正码来纠正通信问题, 自动重复请求(Automatic Repeat Request, ARQ). 分组重新排序, 分组复制, 分组丢 ...
- 第二周 数据分析之展示 Matplotlib库入门
Matplotlib库介绍:优秀的数据可视化第三方库 使用:Matplotlib库由各种可视化类构成,内部结构复杂,受Matlab启发,matplotlib.pyplot是绘制各类可视化图形的命令子库 ...
- git提交忽略某些文件或文件夹
记得第一次用 github 提交代码,node_modules 目录死活传不上去,哈哈哈,后来才知道在 .gitignore 文件里设置了忽略 node_modules 目录上传.是的, .gitig ...
- Linux 运维工作中的经典应用ansible(批量管理)Docker容器技术(环境的快速搭建)
一 Ansible自动化运维工具 Python 在运维工作中的经典应用 ansible(批量管理操作) .安装ansible(需要bese epel 2种源) wget -O /etc/yum.rep ...