Hibernate - @Transactional是否有任何特殊原因?

时间:2014-08-06 00:04:41

标签: java spring hibernate orm transactional

我有一个服务需要会话来创建SQL查询然后执行它。就这些。我在顶级方法上有一个@Transactional,但最终仍然会发生这种情况:

org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
     at org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63)
     at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:687)
     at dao.DaoRunner.getCurrentSession(DaoRunner.java:109)
     at dao.DaoRunner.createSQLQuery(DaoRunner.java:170)
     at dao.DaoRunner$$FastClassByCGLIB$$902af9f8.invoke(<generated>)
     at org.springframework.internal.cglib.proxy.MethodProxy.invoke(MethodProxy.java:149)
     at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:618)
     at dao.DaoRunner$$EnhancerByCGLIB$$484f17ac.createSQLQuery(<generated>)
     at SOME OTHER CLASSES
     at org.apache.catalina.valves.SSLValve.invoke(SSLValve.java:113)
     at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)
     at org.apache.coyote.http11.Http11NioProcessor.process(Http11NioProcessor.java:894)
     at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:728)
     at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:2108)
     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
     at java.lang.Thread.run(Thread.java:745)

DaoRunner类是由Spring自动连接的,包含会话工厂。这是createSQLQuery方法:

public Query createSQLQuery(final String sql) {
    return getCurrentSession().createSQLQuery(sql);
}

这是getCurrentSession()方法:

public Session getCurrentSession() throws HibernateException {
    if (null == sessionFactory) {
        throw new HibernateException(
                "SessionFactory in DaoRunner is not wired.");
    }
    return sessionFactory.getCurrentSession();
}

我的顶级方法是:

@Transactional
public Result run() {
    try {
        String inputData = input.getInputData();

        Result result = aClass.doSomething(inputData);

        return result;
    } catch (Exception e) {
        String msg = ERROR_PREFIX + e;
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        String stackTrace = sw.toString();
        log.error(stackTrace);
        throw new PermanentException(msg);
    }
}

这是sessionFactory bean:

 <bean id="AbstractSessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
        abstract="true">
   <property name="packagesToScan">
     <list>
       <value>apackage</value>
     </list>
   </property>
   <property name="exposeTransactionAwareSessionFactory">
     <value>true</value>
   </property>
 </bean>

<bean id="sessionFactory"
      class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
      parent="AbstractSessionFactory" depends-on="AppConfigHelper">
    <property name="hibernateProperties">
      <props>
         <prop key="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</prop>
         <prop key="hibernate.connection.pool_size">12</prop>             
         <prop key="hibernate.connection.driver_class">${OCF.JDBC.driverClassName}</prop>
         <prop key="hibernate.connection.url">${OCF.JDBC.databaseURL}</prop>
         <prop key="hibernate.connection.username">${OCF.JDBC.databaseUsername}</prop>
         <prop key="hibernate.connection.password">${OCF.JDBC.databasePassword}</prop>

         <prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
         <prop key="hibernate.default_schema">${default.schema}</prop>

         <prop key="hibernate.jdbc.batch_size">1000</prop> 
         <prop key="hibernate.show_sql">false</prop>
         <prop key="hibernate.format_sql">false</prop>

         <prop key="hibernate.c3p0.timeout">44000 <!-- seconds --></prop>

         <prop key="hibernate.c3p0.min_size">#{ '5'}</prop>
         <prop key="hibernate.c3p0.max_size">#{ '5'}</prop>
         <prop key="hibernate.c3p0.initial_pool_size">#{ '5'}</prop>
         <prop key="hibernate.c3p0.idle_test_period">#{  '60'}</prop>
         <prop key="hibernate.c3p0.acquire_increment">#{'2'}</prop>
         <prop key="hibernate.c3p0.max_statements">50</prop>

         <prop key="hibernate.connection.oracle.jdbc.ReadTimeout">60000</prop>
      </props>
    </property>
</bean>

<tx:annotation-driven transaction-manager="txManager" proxy-target-class="true" />

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

请注意,我没有写过大部分内容。我添加了我的顶级方法和createSQLQuery()方法。

2 个答案:

答案 0 :(得分:3)

必须在IOC容器中注册的bean上调用用run注释的@Transactional方法。

要使此类成为bean,您可以在XML配置中注册它,或者只需在XML配置中使用@Component注释和设置组件扫描来注释该类。然后从容器中注入bean并调用run方法。

简单地说,需要从IOC容器中注入的bean调用run方法。

答案 1 :(得分:1)

您需要在spring配置中设置事务管理器,如下所示:

<!-- Enable Annotations for Transaction Management -->
    <tx:annotation-driven transaction-manager="transactionManager" />

    <!-- Creating TransactionManager, change class based on your requirement. -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>