`
snoopy7713
  • 浏览: 1169567 次
  • 性别: Icon_minigender_2
  • 来自: 火星郊区
博客专栏
Group-logo
OSGi
浏览量:0
社区版块
存档分类
最新评论

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

阅读更多

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

发现存在一些问题:
需要配置多个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

 

 

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

 

<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>  
 
分享到:
评论

相关推荐

    spring4+hibernate4+jpa 附有jar包

    在Spring4中集成Hibernate4和JPA,可以实现强大的数据持久化能力。Spring通过其声明式事务管理,使得事务处理变得简单。同时,Spring的JPA支持提供了Repository接口,使得数据访问如同操作普通的Java对象一样方便。...

    Spring之Spring2.5集成Hibernate3.6

    在实际集成过程中,开发者需要配置Spring的Hibernate模板或JPA支持,创建SessionFactory或EntityManagerFactory,然后定义数据访问对象(DAO),并利用Spring的依赖注入将它们注入到业务服务(Service)中。...

    ssh+frameset 简单实例

    在权限管理系统中,frameset常用来分割页面,如顶部导航、左侧菜单和主要内容区域,通过改变不同框架的内容来实现动态页面切换。 在本实例中,"purview_control"可能代表权限控制相关的类或配置文件。这通常涉及到...

    hibernate 3.2.6架包(包括所有jar,eg,api)

    7. 兼容性:Hibernate 3.2.6版本兼容Java 5及更高版本,并且可以与Spring框架等其他Java企业级开发工具集成,以实现更复杂的应用场景。 8. 性能优化:在3.2.6版本中,Hibernate已经进行了大量的性能优化,包括查询...

    乌兰察布市-察哈尔右翼中旗-街道行政区划_150927_Shp数据-wgs84坐标系.rar

    街道级行政区划shp矢量数据,wgs84坐标系,下载直接使用

    张家口市-阳原县--街道行政区划_130727_Shp-wgs84坐标系.rar

    街道级行政区划shp数据,wgs84坐标系,直接下载使用。

    太远市-晋源区-街道行政区划_140110_Shp数据-wgs84坐标系.rar

    街道级行政区划shp矢量数据,wgs84坐标系,下载直接使用

    轻量级密码算法LBlock的FPGA优化实现.docx

    轻量级密码算法LBlock的FPGA优化实现.docx

    吕梁市-岚县-街道行政区划_141127_Shp数据-wgs84坐标系.rar

    街道级行政区划shp矢量数据,wgs84坐标系,下载直接使用

    Git 资料 progit-zh-v2.1.1.pdf

    Git 资料 progit-zh-v2.1.1.pdf

    张家口市-下花园区--街道行政区划_130706_Shp-wgs84坐标系.rar

    街道级行政区划shp数据,wgs84坐标系,直接下载使用。

    篮球计分器FPGA附程序..doc

    篮球计分器FPGA附程序..doc

    秦皇岛市-卢龙县--街道行政区划_130324_Shp-wgs84坐标系.rar

    街道级行政区划shp数据,wgs84坐标系,直接下载使用。

    【Linux开发】Linux开发相关资源教程:涵盖开发环境搭建、基础命令、编程语言及内核开发全攻略

    内容概要:本文档全面介绍了Linux开发的基础知识、应用场景、环境搭建、常用命令、Shell脚本编程以及C/C++和Python开发等内容。首先阐述了Linux开发的重要性及其在服务器端开发、嵌入式开发和系统运维等领域的广泛应用。接着详细讲解了如何选择合适的Linux发行版并安装系统,配置开发环境,包括安装必要的开发工具和配置SSH服务。文档还深入讲解了Linux基础命令,如文件和目录操作、文件内容查看与编辑、进程管理和权限管理。此外,介绍了Shell脚本编程的基本语法,包括变量、条件语句、循环语句和函数定义。针对C/C++和Python开发,文档分别讲解了编译器安装、程序编写与编译、调试方法及使用虚拟环境等内容。最后,简要介绍了Linux内核开发的相关知识,包括下载编译内核、内核模块开发等,并推荐了相关学习资源。 适合人群:对Linux开发感兴趣的初学者及有一定经验的研发人员,尤其是希望深入掌握Linux开发技能的开发者。 使用场景及目标:①掌握Linux开发环境的搭建与配置;②熟悉Linux基础命令和Shell脚本编程;③学习C/C++和Python在Linux下的开发流程;④了解Linux内核开发的基本概念和技术。 阅读建议:此文档内容丰富,涵盖面广,建议读者根据自身需求选择性阅读,并结合实际操作进行练习。特别是对于初学者,应先掌握基础命令和开发环境的搭建,再逐步深入到编程语言和内核开发的学习。

    石家庄市-石家庄市-石家庄市-石家庄市-街道行政区划_130100_Shp数据wgs84坐标系.rar

    街道级行政区划shp数据,wgs84坐标系,直接下载使用。

    石家庄市-石家庄市-石家庄市-无极县-街道行政区划_130130_Shp数据wgs84坐标系.rar

    街道级行政区划shp数据,wgs84坐标系,直接下载使用。

    保定市-易县--街道行政区划_130633_Shp-wgs84坐标系.rar

    街道级行政区划shp数据,wgs84坐标系,直接使用。

    【办公软件应用】Word文档编辑与排版练习题集:涵盖内容编辑、页面布局及高效文档技巧

    内容概要:本文档《word练习题.docx》是一份详细的Word操作练习指南,涵盖了从基础到高级的各种功能。文档分为三个主要部分:内容编辑、页面布局和高效文档。内容编辑部分包括文本格式化、段落设置、项目编号、制表位、边框与底纹等练习;页面布局部分涉及分节符、分栏、页眉页脚、水印等设置;高效文档部分则聚焦于样式管理、导航窗格、题注、书签、超级链接、脚注与尾注、交叉引用等功能。每个练习都有具体的操作步骤,帮助用户掌握Word的各种实用技巧。 适合人群:适用于Word初学者及希望提高Word技能的中级用户,尤其是需要频繁使用Word进行文档编辑和排版的办公人员。 使用场景及目标:①帮助用户熟悉Word的基本操作,如文本编辑、格式设置等;②提升用户的文档排版能力,学会设置复杂的页面布局;③提高工作效率,掌握高效文档管理技巧,如样式应用、题注和交叉引用等。 其他说明:此文档不仅提供了具体的练习题目,还附带了详细的步骤说明,用户可以根据指引逐步完成每个练习。此外,文档中的一些练习涉及到智能文档和Office智能客户端的应用,有助于用户了解Word在企业级应用中的潜力。建议用户按照章节顺序逐步学习,实践每一个练习,以达到最佳的学习效果。

    邢台市-信都区--街道行政区划_130503_Shp-wgs84坐标系.rar

    街道级行政区划shp数据,wgs84坐标系,直接下载使用。

    腐败感知指数(CPI)数据和各种治理指标数据集

    全球腐败感知数据(2000-2023)——3000行 33个指标 关于数据集 该数据集包含3000行和33列,涵盖了2000年至2023年的腐败感知指数(CPI)数据和各种治理指标。它包括国家排名、分数和其他指标,如公共部门腐败、司法腐败、贿赂指数、商业道德、民主指数、法治、政府效率、经济指标和人类发展指数。 这些数据可用于: 腐败趋势分析 腐败对GDP、人类发展指数和治理的影响 跨国比较 数据可视化和机器学习模型 该数据集对研究人员、数据分析师、政策制定者和对研究全球腐败趋势非常有用。

Global site tag (gtag.js) - Google Analytics