`
danwind
  • 浏览: 223206 次
  • 性别: Icon_minigender_1
  • 来自: 广东
社区版块
存档分类
最新评论

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

 
阅读更多

 

前面写了一篇关于动态切换Hibernate SessionFactory的文章,原文地址:http://tangyanbo.iteye.com/admin/blogs/1717402

发现存在一些问题:
需要配置多个HibernateTransactionManager和多个Spring 切面
这样带来两个问题
1. 程序效率降低,因为Spring进行多次Advice的拦截
2. 如果其中一个SessionFactory连接出现问题,会导致整个系统无法工作

今天研究出一种新的方法来解决此类问题
1. 数据源及Hibernate SessionFactory配置:

 

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>    
  2. <beans xmlns="http://www.springframework.org/schema/beans"    
  3.     xmlns:p="http://www.springframework.org/schema/p"    
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"    
  5.     xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"    
  6.     xsi:schemaLocation="    
  7.             http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    
  8.             http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd    
  9.             http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd    
  10.             http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">    
  11.     <!-- FOR SqlServer-->    
  12.     <bean id="SqlServer_DataSource"    
  13.         class="org.springframework.jdbc.datasource.DriverManagerDataSource">    
  14.         <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />    
  15.         <property name="url"    
  16.             value="url" />    
  17.         <property name="username" value="username" />    
  18.         <property name="password" value="password" />    
  19.     </bean>    
  20.     <bean id="SqlServer_SessionFactory"    
  21.         class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"    
  22.         p:mappingLocations="classpath:/com/entity/*.hbm.xml">    
  23.         <property name="dataSource" ref="SqlServer_DataSource" />         
  24.         <property name="hibernateProperties">    
  25.             <props>                   
  26.                 <prop key="hibernate.query.factory_class">org.hibernate.hql.ast.ASTQueryTranslatorFactory</prop>    
  27.                 <prop key="hibernate.dialect">org.hibernate.dialect.SQLServer2008Dialect</prop>                 
  28.                 <prop key="hibernate.show_sql">true</prop>    
  29.                 <prop key="hibernate.format_sql">true</prop>    
  30.             </props>    
  31.         </property>    
  32.     </bean>    
  33.      
  34.         
  35.     <!-- FOR Oracle -->    
  36.     <bean id="Oracle _DataSource"    
  37.         class="org.springframework.jdbc.datasource.DriverManagerDataSource">         
  38.         <property name="driverClassName" value="oracle.jdbc.OracleDriver" />    
  39.         <property name="url" value="jdbc:oracle:thin:@localhost:1521/orcl" />    
  40.         <property name="username" value="username" />    
  41.         <property name="password" value="password" />    
  42.     </bean>    
  43.     <bean id="Oracle_SessionFactory"    
  44.         class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"     
  45.         p:mappingLocations="classpath:/com/entity/*.hbm.xml">    
  46.         <property name="dataSource" ref="Oracle_DataSource" />            
  47.         <property name="hibernateProperties">    
  48.             <props>    
  49.                 <prop key="hibernate.query.factory_class">org.hibernate.hql.ast.ASTQueryTranslatorFactory</prop>    
  50.                 <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>                 
  51.                 <prop key="hibernate.show_sql">true</prop>    
  52.                 <prop key="hibernate.format_sql">true</prop>    
  53.             </props>    
  54.         </property>    
  55.     </bean>    
  56.     
  57.         
  58.         
  59. </beans>    

 

2. 定义扩展接口DynamicSessionFactoryInf继承SessionFactory

 

 

Java代码  收藏代码
  1. import org.hibernate.SessionFactory;  
  2.   
  3. public interface DynamicSessionFactoryInf extends SessionFactory {  
  4.   
  5.     public SessionFactory getHibernateSessionFactory();  
  6. }  

 

3. 定义DynamicSessionFactory实现DynamicSessionFactoryInf

 

Java代码  收藏代码
  1. public class DynamicSessionFactory implements DynamicSessionFactoryInf ,ApplicationContextAware{  
  2.       
  3.     private static final long serialVersionUID = 1L;  
  4.   
  5.     private ApplicationContext applicationContext;  
  6.     //动态调用SessionFactory  
  7.     private SessionFactory getHibernateSessionFactory(String name) {  
  8.         return (SessionFactory) applicationContext.getBean(name);  
  9.     }  
  10.         //实现DynamicSessionFactoryInf 接口的方法  
  11.     public SessionFactory getHibernateSessionFactory() {  
  12.         return getHibernateSessionFactory(ThreadLocalUtil.getCurrentITAsset()  
  13.                 .getSessionFactoryName());  
  14.     }  
  15.       
  16.        //以下是实现SessionFactory接口的方法,并对当前的SessionFactory实体进行代理  
  17.     public Reference getReference() throws NamingException {  
  18.         return getHibernateSessionFactory().getReference();  
  19.     }  
  20.   
  21.       
  22.   
  23.     public Session openSession() throws HibernateException {  
  24.         return getHibernateSessionFactory().openSession();  
  25.     }  
  26.   
  27.     public Session openSession(Interceptor interceptor)  
  28.             throws HibernateException {  
  29.         return getHibernateSessionFactory().openSession(interceptor);  
  30.     }  
  31.   
  32.     public Session openSession(Connection connection) {  
  33.         return getHibernateSessionFactory().openSession(connection);  
  34.     }  
  35.   
  36.     public Session openSession(Connection connection, Interceptor interceptor) {  
  37.         return getHibernateSessionFactory().openSession(connection,interceptor);  
  38.     }  
  39.   
  40.     public Session getCurrentSession() throws HibernateException {  
  41.         return getHibernateSessionFactory().getCurrentSession();  
  42.     }  
  43.   
  44.     public StatelessSession openStatelessSession() {  
  45.         return getHibernateSessionFactory().openStatelessSession();  
  46.     }  
  47.   
  48.     public StatelessSession openStatelessSession(Connection connection) {  
  49.         return getHibernateSessionFactory().openStatelessSession(connection);  
  50.     }  
  51.   
  52.     public ClassMetadata getClassMetadata(Class entityClass) {  
  53.         return getHibernateSessionFactory().getClassMetadata(entityClass);  
  54.     }  
  55.   
  56.     public ClassMetadata getClassMetadata(String entityName) {  
  57.         return getHibernateSessionFactory().getClassMetadata(entityName);  
  58.     }  
  59.   
  60.     public CollectionMetadata getCollectionMetadata(String roleName) {  
  61.         return getHibernateSessionFactory().getCollectionMetadata(roleName);  
  62.     }  
  63.   
  64.     public Map getAllClassMetadata() {  
  65.         return getHibernateSessionFactory().getAllClassMetadata();  
  66.     }  
  67.   
  68.     public Map getAllCollectionMetadata() {  
  69.         return getHibernateSessionFactory().getAllCollectionMetadata();  
  70.     }  
  71.   
  72.     public Statistics getStatistics() {  
  73.         return getHibernateSessionFactory().getStatistics();  
  74.     }  
  75.   
  76.     public void close() throws HibernateException {  
  77.         getHibernateSessionFactory().close();  
  78.     }  
  79.   
  80.     public boolean isClosed() {  
  81.         return getHibernateSessionFactory().isClosed();  
  82.     }  
  83.   
  84.     public Cache getCache() {  
  85.         return getHibernateSessionFactory().getCache();  
  86.     }  
  87.   
  88.     public void evict(Class persistentClass) throws HibernateException {  
  89.         getHibernateSessionFactory().evict(persistentClass);  
  90.     }  
  91.   
  92.     public void evict(Class persistentClass, Serializable id)  
  93.             throws HibernateException {  
  94.         getHibernateSessionFactory().evict(persistentClass, id);  
  95.     }  
  96.   
  97.     public void evictEntity(String entityName) throws HibernateException {  
  98.         getHibernateSessionFactory().evictEntity(entityName);  
  99.     }  
  100.   
  101.     public void evictEntity(String entityName, Serializable id)  
  102.             throws HibernateException {  
  103.         getHibernateSessionFactory().evictEntity(entityName, id);  
  104.     }  
  105.   
  106.     public void evictCollection(String roleName) throws HibernateException {  
  107.         getHibernateSessionFactory().evictCollection(roleName);  
  108.     }  
  109.   
  110.     public void evictCollection(String roleName, Serializable id)  
  111.             throws HibernateException {  
  112.         getHibernateSessionFactory().evictCollection(roleName, id);  
  113.     }  
  114.   
  115.     public void evictQueries(String cacheRegion) throws HibernateException {  
  116.         getHibernateSessionFactory().evictQueries(cacheRegion);  
  117.     }  
  118.   
  119.     public void evictQueries() throws HibernateException {  
  120.         getHibernateSessionFactory().evictQueries();  
  121.     }  
  122.   
  123.     public Set getDefinedFilterNames() {  
  124.         return getHibernateSessionFactory().getDefinedFilterNames();  
  125.     }  
  126.   
  127.     public FilterDefinition getFilterDefinition(String filterName)  
  128.             throws HibernateException {  
  129.         return getHibernateSessionFactory().getFilterDefinition(filterName);  
  130.     }  
  131.   
  132.     public boolean containsFetchProfileDefinition(String name) {  
  133.         return getHibernateSessionFactory().containsFetchProfileDefinition(name);  
  134.     }  
  135.   
  136.     @Override  
  137.     public void setApplicationContext(ApplicationContext applicationContext)  
  138.             throws BeansException {  
  139.         this.applicationContext = applicationContext;  
  140.     }  
  141.   
  142.       
  143.   
  144. }  

 

4. 配置动态SessionFactory

 

Xml代码  收藏代码
  1. <bean id="sessionFactory" class="com.hp.it.qdpadmin.common.DynamicSessionFactory"/>   
 

 

5. 定义DynamicTransactionManager继承HibernateTransactionManager

 

Java代码  收藏代码
  1. public class DynamicTransactionManager extends HibernateTransactionManager {  
  2.   
  3.     private static final long serialVersionUID = 1047039346475978451L;  
  4.     //重写getDataSource方法,实现动态获取  
  5.     public DataSource getDataSource() {  
  6.         DataSource sfds = SessionFactoryUtils.getDataSource(getSessionFactory());  
  7.         return sfds;  
  8.     }  
  9.        //重写getSessionFactory方法,实现动态获取SessionFactory  
  10.     public SessionFactory getSessionFactory() {  
  11.         DynamicSessionFactoryInf dynamicSessionFactory = (DynamicSessionFactoryInf) super  
  12.                 .getSessionFactory();  
  13.         SessionFactory hibernateSessionFactory = dynamicSessionFactory  
  14.                 .getHibernateSessionFactory();  
  15.         return hibernateSessionFactory;  
  16.     }  
  17.     //重写afterPropertiesSet,跳过数据源的初始化等操作  
  18.     public void afterPropertiesSet() {  
  19.         return;  
  20.     }  
  21.   
  22. }  

 

6. 配置dynamicTransactionManager

 

Xml代码  收藏代码
  1. <bean id="dynamicTransactionManager"  
  2.         class="com.hp.it.qdpadmin.common.DynamicTransactionManager">  
  3.         <property name="sessionFactory" ref="sessionFactory"/>  
  4.     </bean>  
 

 

7. 为SessionFactory配置事务切面

 

Xml代码  收藏代码
  1. <tx:advice id="dynamicTxAdvice" transaction-manager="dynamicTransactionManager">    
  2.         <tx:attributes>    
  3.             <tx:method name="get*" read-only="true" />    
  4.             <tx:method name="find*" read-only="true" />    
  5.             <tx:method name="*" propagation="REQUIRED" rollback-for="Exception" />    
  6.         </tx:attributes>    
  7.     </tx:advice>    
  8.         
  9.         
  10.     <aop:config proxy-target-class="true">      
  11.         <aop:pointcut id="txPointcut" expression="execution(* com.service.*.*(..))"/>            
  12.         <aop:advisor advice-ref="dynamicTxAdvice" pointcut-ref="txPointcut" />   
  13.     </aop:config>    
 

 

分享到:
评论

相关推荐

    Spring+hibernate+quartz 定时操作数据库

    在spring+hibernate的框架中定时操作数据库,主要是拿到sessionFactory,不会出现no session 和transaction no-bound等问题,由sessionFactory完成对数据的操作,有些包是没有用的,有兴趣的可以自己删除掉

    搞定J2EE:STRUTS+SPRING+HIBERNATE整合详解与典型案例 (1)

    12.6 整合Struts、Spring和Hibernate实现用户管理 12.6.1 Struts、Spring和Hibernate的整合方式 12.6.2 编写用户注册画面regedit.jsp 12.6.3 编写用户登录画面login.jsp 12.6.4 编写注册控制器RegeditAction.java ...

    Spring4.0+Hibernate4.0+Struts2.3整合案例

    Spring4.0+Hibernate4.0+Struts2.3整合案例:实现增删改查。 ===================== application.xml: xmlns="http://www.springframework.org/schema/beans" xmlns:xsi=...

    Spring+Jotm+Hibernate+Oracle+Junit 实现JTA分布式事务要求Demo工程

    2.Spring+Jotm整合实现JTA分布式事务,应用场景如转账等,同一事务内完成db1用户加100元、db2用户减100元。 3.Spring+Junit4单元测试,优点:不会破坏数据库现场,等等。 (特别注意:Spring3.0里不在提供对jotm的...

    Struts2+Hibernate+Spring整合实例

    Struts2+Hibernate+Spring整合实例,登陆注册实例,简单来说,Spring通过IoC容器上管(Struts2)Action的创建并依赖注入给控制器,下管(hibernate)SessionFactory的创建并依赖注入给DAO组件,是一个巨大的工厂

    spring配置sessionFactory(spring3.2.3+hibernate4.2.2)

    一个实例小工程,讲解的是将hibernate的sessionFactory交给spring管理的配置方法

    搞定J2EE:STRUTS+SPRING+HIBERNATE整合详解与典型案例 (2)

    12.6 整合Struts、Spring和Hibernate实现用户管理 12.6.1 Struts、Spring和Hibernate的整合方式 12.6.2 编写用户注册画面regedit.jsp 12.6.3 编写用户登录画面login.jsp 12.6.4 编写注册控制器RegeditAction.java ...

    搞定J2EE:STRUTS+SPRING+HIBERNATE整合详解与典型案例 (3)

    12.6 整合Struts、Spring和Hibernate实现用户管理 12.6.1 Struts、Spring和Hibernate的整合方式 12.6.2 编写用户注册画面regedit.jsp 12.6.3 编写用户登录画面login.jsp 12.6.4 编写注册控制器RegeditAction.java ...

    Spring + Hibernate + Struts 事务配置小例子(带提示框等小技巧)

    前几天搞 Spring + Hibernate + Struts 事务配置 ,网上找了好多资料,不过好无语,大多都是 Ctrl + V,浪费俺的宝贵时间 现在我总结配出一套,给大家参考参考,可能有不足,请大家多多交流。 附:内有弹出...

    ssh框架整合step by step (springMVC + spring 5.0.4 + hibernate 5.0.12)

    # 不熟悉git的同学也没关系, 根据不同搭建进度, 资源内分别打了三个项目(springmvc、springmvc+spring、springmvc+spring+hibernate), 可逐个对比查看; # 项目主要描述ssh的搭建步骤, 前端仅仅是几个简单的展示页面;...

    基于J2EE短信共享网站设计(Spring+Struts2+Hibernate)

    基于三大框架架构Spring+Struts2+Hibernate 这个是我毕业设计,有论文,也有答辩ppt,开题报告... 比较成功,所以传上来与大家分享。 界面采用新浪界面样式, 后台层次非常清晰。 数据库采用MySql。 服务器用tomcat...

    利用Spring来管理Hibernate完整例子

    其中Hibernate每次都需要手动创建SessionFactory,Session,手动开启提交关闭事务。而这一切操作完全是由Spring来代替。使持久层更加方便,使开发人员减少持久层操作,把注意力放到业务上。

    Struts+Spring+Hibernate补充内容

    在SSH中实现以下功能时, 需要将Tomcat中站点目录下/WEB-INF/lib 中的asm-2.2.3.jar和commons-collections-2.1.1.jar 文件删除,否则会引起类冲突 分离配置文件: 在src目录下创建多个xml文件,分别配制项目中的 ...

    spring2.5+struts2+hibernate3.3整合

    这是一个spring2.5+struts2+hibernate3.3的整合完整项目,struts2的ActionBean,hibernate的sessionFactory交与了spring容器创建与管理

    springMVC + Hibernate 工程模板

    两种配置:oracle mysql,切换数据库只要把SessionFactory的配置文件改成对应就可以了 c3p0配置:mysql调试通过,oracle由于存在问题,未配置 spring配置式事务管理(jdk动态代理,每个service必须对应一个接口) ...

    spring2.5+hibernate3.3+struts1.3的整合

    一个spring2.5+hibernate3.3+struts1.3的整合的完整项目,该项目使用spring容器创建sessionFactory,管理struts ActionBean的创建,其中使用注解的方式创建实体Bean以及依赖注入和事务

    NewsSystem:基于Struts + Spring + Hibernate + Bootstrap

    基于SSH的Java EE新闻发布系统项目介绍基于Struts + Spring + Hibernate + Bootstrap技术开发的新闻发布系统。系统功能:前台为管理员对新闻以及新闻栏目的CRUD操作,新闻审核,权限以及角色的控制等。技术选型初步...

    Myeclipse开发struts+hibernate+spring新手入门--环境配置---项目开发示例

    Myeclipse开发struts+hibernate+spring新手入门---环境配置----项目开发示例 Myeclipse开发struts+hibernate+spring小记 开发前准备工作: 1、下载eclipse3.1版本 下载地址: 2、下载Myeclipse插件 下载地址: 3...

    Struts,Spring,Hibernate三大框架的面试&笔试题

    1.Hibernate工作原理及为什么要用? 原理: 1.读取并解析配置文件 2.读取并解析映射信息,创建SessionFactory 3.打开Sesssion 4.创建事务Transation 5.持久化操作 6.提交事务 7.关闭Session 8.关闭...

    Hibernate中的sessionFactory

    Hibernate中的sessionFactory

Global site tag (gtag.js) - Google Analytics