ITeye博客

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

snoopy7713 · 2012-11-09 14:11 · spring · 企业架构 · Spring · Hibernate · Markdown

前面写了一篇关于动态切换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. public   interface  DynamicSessionFactoryInf  extends  SessionFactory {
  3. public  SessionFactory getHibernateSessionFactory();
  4. }

 

3. 定义DynamicSessionFactory实现DynamicSessionFactoryInf

 

Java代码  收藏代码

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

 

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. private   static   final   long  serialVersionUID = 1047039346475978451L;
  3. //重写getDataSource方法,实现动态获取
  4. public  DataSource getDataSource() {
  5. DataSource sfds = SessionFactoryUtils.getDataSource(getSessionFactory());
  6. return  sfds;
  7. }
  8. //重写getSessionFactory方法,实现动态获取SessionFactory
  9. public  SessionFactory getSessionFactory() {
  10. DynamicSessionFactoryInf dynamicSessionFactory = (DynamicSessionFactoryInf) super
  11. .getSessionFactory();
  12. SessionFactory hibernateSessionFactory = dynamicSessionFactory
  13. .getHibernateSessionFactory();
  14. return  hibernateSessionFactory;
  15. }
  16. //重写afterPropertiesSet,跳过数据源的初始化等操作
  17. public   void  afterPropertiesSet() {
  18. return ;
  19. }
  20. }

 

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>  

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。