8

我正在将我的项目从 Spring 3.0 +hibernate 3.6.x 迁移到 S3.1 + H4.1

我的新代码如下

    <context:component-scan base-package="x.y.z">
</context:component-scan>

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="hibernateProperties">
 <props>
    <prop key="hibernate.dialect">org.hibernate.dialect.x</prop> 
    <prop key="hibernate.show_sql">true</prop> 
    <prop key="hibernate.hbm2ddl.auto">update</prop> 
    <prop key="hibernate.show_sql">true</prop> 
  </props>
     </property>
        <property name="annotatedClasses">
      <list>
        <value>x.y.z.entities.Student</value>        
         </list>
    </property>
  </bean>

<bean id="transactionManager" 
            class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory"/>
  </bean>

<aop:config>
    <aop:pointcut id="daoServicePoint" 
            expression="execution(* x.y.z.StudentDao.*(..))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="daoServicePoint"/>
  </aop:config>

  <tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
      <tx:method name="save*" propagation="REQUIRED"/>
       <tx:method name="update*" propagation="REQUIRED"/>
       <tx:method name="delete*" propagation="REQUIRED"/>
     <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
    </tx:attributes>
  </tx:advice> 

当运行 getStudent 方法标记作为支持并且只读我得到

org.hibernate.HibernateException: No Session found for current thread
    at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)
    at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1024)

Spring 3.0 和 Hibernate 3.6.x 以前没问题,现在它被改变了。我从 Spring 论坛中发现,如果我需要使用,我需要标记事务 REQUIREDsessionFactory.getCurrentSession();

为了在我的代码中获得最大的并发速度,我使用了较低级别的技术。在执行需要多个 get/save/update/ 查询的操作时,我按照以下方式进行操作:

  1. 被调用的方法标记为SUPPORTS
  2. 执行了所有获取查询,这些查询也被标记为SUPPORTS内部第一种方法。
  3. 然后开始在同一方法内标记为的查询,REQUIRED这是我的可回滚事务开始的地方。

使用这种技术我得到了很好的性能改进,但是将我所有的方法标记为 REQUIRED 会破坏它。

如何解决它?

4

2 回答 2

3

我在试验 Spring 和 Hibernate 3 / 4 时遇到了同样的问题。

看起来这是一个已知问题,在以下 JIRA 链接中进行了描述。

https://jira.springsource.org/browse/SPR-9020

如果没有打开现有的事务/会话并且调用的方法@Transactional 配置为propagation = Propagation.SUPPORTS,则看起来Hibernate 4 版本的SpringSessionContext 不会打开新会话。

于 2013-08-24T17:38:18.643 回答
0

我认为您仍然可以将事务标记为只读。不确定它是否对性能有影响。

于 2012-07-02T19:04:25.007 回答