Hibernate - @Transactional 不起作用有啥特别的原因吗?

Posted

技术标签:

【中文标题】Hibernate - @Transactional 不起作用有啥特别的原因吗?【英文标题】:Hibernate - Is there any particular reason that an @Transactional isn't working?Hibernate - @Transactional 不起作用有什么特别的原因吗? 【发布时间】:2014-08-06 00:04:40 【问题描述】:

我有一个服务需要一个会话来创建一个 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() 方法。

【问题讨论】:

【参考方案1】:

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

要使此类成为 bean,您可以在 XML 配置中注册它,或者简单地使用 @Component 注释对类进行注释,并在 XML 配置中设置组件扫描。然后从容器中注入bean并调用run方法。

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

【讨论】:

这是我的问题!谢谢! @jchitel 很高兴我能帮上忙!【参考方案2】:

您需要在 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>

【讨论】:

好点,我错过了!另外,我认为tx:annotation-driven 标签必须包含在 XML 配置中。 我不知道你有多想看。我已经使用事务管理器配置更新了我的帖子

以上是关于Hibernate - @Transactional 不起作用有啥特别的原因吗?的主要内容,如果未能解决你的问题,请参考以下文章

oracle rollback 观察时间

重学SpringBoot系列之Mockito测试

MongoDB4.2分布式事务

区块链之智能合约 solidity踩坑 --上篇

注意Spring事务这一点,避免出现大事务

注意Spring事务这一点,避免出现大事务