Hibernate中有许多线程查询.org.hibernate.HibernateException: get在没有活动



我有一个应用程序,我正在创建许多线程。它们具有要查询的会话的属性(该属性先前已配置)。

当我尝试查询时,我得到了这个异常:org.hibernate.HibernateException: get在没有活动事务的情况下无效

我一直在阅读会话,会话不能在线程之间共享,我想知道解决这个问题的最佳方法是什么。我只能为每个线程打开一个新连接吗?

  public Configuration get(final String id) {
            final Session session = sessionFactory.getCurrentSession(); //it works with openSession..
            final Configuration object =
                    (Configuration) session.get(Configuration.class.getName(),
                            id);
            return object;
        }

    <property name="hibernateProperties">
                <props>
                    <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                    <prop key="hibernate.connection.autocommit">false</prop>
                    <prop key="hibernate.show_sql">false</prop>
                    <!-- <prop key="current_session_context_class">thread</prop>--> 
                    <prop key="hibernate.current_session_context_class">thread</prop>
                    <prop key="hibernate.hbm2ddl.auto">validate</prop>
                    <prop key="hibernate.c3p0.min_size">2</prop>
                    <prop key="hibernate.c3p0.max_size">125</prop>
                    <prop key="hibernate.c3p0.timeout">1800</prop>
                    <prop key="hibernate.c3p0.max_statements">500</prop>
                </props>
            </property>

<bean id="transactionManager"
    class="com.pragsis.bidoop.data.tx.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="txTemplate" abstract="true"
    class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
    <property name="transactionManager" ref="transactionManager" />
    <property name="transactionAttributes">
        <props>
            <prop key="get*">
                PROPAGATION_SUPPORTS,ISOLATION_READ_UNCOMMITTED,readOnly
            </prop>
            <prop key="list*">
                PROPAGATION_SUPPORTS,ISOLATION_READ_UNCOMMITTED,readOnly
            </prop>
            <prop key="*">
                PROPAGATION_REQUIRED,ISOLATION_SERIALIZABLE
            </prop>
        </props>
    </property>
</bean>

我已经标记了我在线程上使用的方法,如事务性服务,而不是配置中的get方法,但是,我得到了同样的错误。

我使用Spring来管理事务。

每个事务都是线程绑定的,所以如果你跨越一个新线程,它将无法访问原始线程的事务。

最简单的解决方案是从新创建的线程中调用@Transactional服务:

myService.getSomething();

当这样的@Transactional服务方法被调用时,一个新的Transaction被关联到当前线程,因为你使用Spring,那么你所有的dao都会相应地使用它。

最新更新