ITeye博客

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

danwind · 2014-12-11 18:31 · StrutsSpringHibernate · 编程语言 · Markdown

前面写了一篇关于动态切换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. <!-- FOR Oracle -->
  34. <bean id="Oracle _DataSource"
  35. class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  36. <property name="driverClassName" value="oracle.jdbc.OracleDriver" />
  37. <property name="url" value="jdbc:oracle:thin:@localhost:1521/orcl" />
  38. <property name="username" value="username" />
  39. <property name="password" value="password" />
  40. </bean>
  41. <bean id="Oracle_SessionFactory"
  42. class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"
  43. p:mappingLocations="classpath:/com/entity/*.hbm.xml">
  44. <property name="dataSource" ref="Oracle_DataSource" />
  45. <property name="hibernateProperties">
  46. <props>
  47. <prop key="hibernate.query.factory_class">org.hibernate.hql.ast.ASTQueryTranslatorFactory</prop>
  48. <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
  49. <prop key="hibernate.show_sql">true</prop>
  50. <prop key="hibernate.format_sql">true</prop>
  51. </props>
  52. </property>
  53. </bean>
  54. </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

 

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. <aop:config proxy-target-class="true">
  9. <aop:pointcut id="txPointcut" expression="execution(* com.service.*.*(..))"/>
  10. <aop:advisor advice-ref="dynamicTxAdvice" pointcut-ref="txPointcut" />
  11. </aop:config>

 

转载自:http://tangyanbo.iteye.com/blog/1718643

评论(0)

暂无评论。

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