HibernateTransactionManager

HibernateTransactionManager

我们正在得到错误


  org.springframework.transaction.IllegalTransactionStateException:找到预绑定的JDBC连接!如果告知HibernateTransactionManager管理DataSource本身,则它不支持在DataSourceTransactionManager中运行。无论是Hibernate还是JDBC访问,建议对单个DataSource上的所有事务都使用单个HibernateTransactionManager。


它发生的地方是我们覆盖事务管理器的地方,以便我们可以对doBegin,commit和rollback方法做出反应。但是,该错误发生在doBegin(我们调用super.doBegin())中,并且在我们的任何代码实际运行之前。就我们希望发生的错误而言,错误也是高度断断续续且不合作的。

我在网上看到许多人暗示这通常意味着您定义了两个事务管理器。最初,我拒绝将其应用于我们,因为我们没有这样做。我仔细检查了。但是,不是那么快,也许我愿意。虽然我们的战争只有一个TX管理器,但发生这种情况的应用程序……发生这种情况的唯一应用程序……是同一EAR中的两次战争。每个对象都有自己定义的spring上下文和自己的txManager。他们会发生冲突吗?这可能是我们麻烦的根源吗?

更新-

app-config.xml(至少可能相关的部分...我遗漏了很多平凡的bean定义)

    <bean id="dataSource" name="enoteDataSource dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
            <property name="resourceRef"><value>false</value></property>
            <property name="jndiName">
                <value>${ds.jndi}</value>
            </property>
        </bean>
    <bean id="sessionFactory" name="sessionFactory enoteSessionFactory" class = "org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource"><ref local="dataSource" /></property>
        <property name="packagesToScan">
            <list>
                <value>gov.usdoj.afms.enote.model.*</value>
            </list>
        </property>
    <bean id="txManager" name="txManager transactionManager" class="gov.usdoj.afms.umc.utils.hibernate.AfmsHibernateTransactionManager">
        <property name="sessionFactory" ref="enoteSessionFactory" />
    </bean>
    <!--  some of the transaction are controlled in code through annotation -->
    <tx:annotation-driven transaction-manager="txManager"/>
    <!-- the transactional advice (what 'happens'; see the <aop:advisor/> bean below) -->
    <tx:advice id="txActionAdvice" transaction-manager="txManager">
        <!-- the transactional semantics... -->
        <tx:attributes>
            <tx:method name="deleteUser"  propagation="REQUIRES_NEW" rollback-for="BOException" />
            <tx:method name="*"  propagation="REQUIRES_NEW" />
        </tx:attributes>
    </tx:advice>
    <tx:advice id="txAdvice" transaction-manager="txManager">
     <!-- the transactional semantics... -->
    <tx:attributes>
        <!-- all methods starting with 'fetch' are read-only -->
        <tx:method name="fetch*" isolation="READ_UNCOMMITTED"/>
        <!-- other methods use the default transaction settings (see below) -->
        <tx:method name="*" rollback-for="Throwable" />
    </tx:attributes>
    </tx:advice>
  <aop:config>
   <aop:advisor
      pointcut="execution(* gov.usdoj.afms.umc.services.ActionPanelService.*(..))"
      advice-ref="txActionAdvice"/>

    <aop:advisor
      pointcut="execution(* gov.usdoj.afms.umc.services.AccountInfoService.*(..))"
      advice-ref="txAdvice"/>

   <aop:advisor
      pointcut="execution(* gov.usdoj.afms.umc.services.PersonalInfoService.*(..))"
      advice-ref="txAdvice"/>

   <aop:advisor
      pointcut="execution(* gov.usdoj.afms.umc.services.CreateUserService.*(..))"
      advice-ref="txAdvice"/>

   <aop:advisor
      pointcut="execution(* gov.usdoj.afms.umc.services.UM04Service.*(..))"
      advice-ref="txAdvice"/>

    <aop:advisor
      pointcut="execution(* gov.usdoj.afms.umc.services.LookupService.removeUsrOrgLvlAsgnT(..))"
      advice-ref="txAdvice"/>

    <aop:advisor
      pointcut="execution(* gov.usdoj.afms.umc.services.LookupService.addOrUpdateUsrOrgLvlAsgnT(..))"
      advice-ref="txAdvice"/>

    <aop:advisor
      pointcut="execution(* gov.usdoj.afms.umc.services.LookupService.removeAndAddUsrOrgLvlAsgnT(..))"
      advice-ref="txAdvice"/>

   <aop:advisor
      pointcut="execution(* gov.usdoj.afms.umc.services.St60Service.*(..))"
      advice-ref="txAdvice"/>

  </aop:config>

    <bean id="serviceTarge" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
      <property name="transactionManager" ref="txManager" />
      <property name="target" ref="createUserService" />
      <property name="transactionAttributes">
        <props>
            <prop key="insert*">PROPAGATION_REQUIRED</prop>
            <prop key="update*">PROPAGATION_REQUIRED</prop>
            <prop key="*">PROPAGATION_REQUIRED</prop>
        </props>
      </property>
    </bean>

    <bean id="UM04ServiceTarget" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
      <property name="transactionManager" ref="txManager" />
      <property name="target" ref="UM04Service" />
      <property name="transactionAttributes">
        <props>
            <prop key="*">PROPAGATION_REQUIRED</prop>
        </props>
      </property>
    </bean>

    <bean id="umcLookups" class="gov.usdoj.afms.umc.application.lookups.UMCLookups" init-method="init" scope="singleton">
        <property name="lookupDao" ref="LookupDao"/>
    </bean>

    <bean id="userSearchServiceBean" class="org.springframework.aop.framework.ProxyFactoryBean">
      <property name="proxyInterfaces">
      <value>gov.usdoj.afms.umc.services.UserSearchService</value>
    </property>
        <property name="target">
            <ref bean="userSearchServiceImpl"/>
        </property>
        <property name="interceptorNames">
            <list>
                <value>theLogger</value>
            </list>
        </property>
    </bean>


在那里有txManager替代,因此我们可以为CLIENT_INFO设置一些值,该值使我们能够识别具有事务的用户和模块,因此我们的审计触发器将记录信息。

@Override
protected void doBegin(Object arg0, TransactionDefinition arg1)
{
    super.doBegin(arg0, arg1);
    if (!Db2ClientInfo.exists()) {
        clearDBProperty();
    } else {
        setDBProperty(Db2ClientInfo.getClientUserId(), Db2ClientInfo.getClientApplicationId());
    }
}

@Override
protected void doCommit(DefaultTransactionStatus status) {
    super.doCommit(status);
    clearDBProperty();
}


@Override
protected void doRollback(DefaultTransactionStatus status) {
    super.doRollback(status);
    clearDBProperty();
}

@SuppressWarnings("deprecation")
private void setDBProperty(String uId, String appName) {
    Session session = getSessionFactory().getCurrentSession();

    Properties props = new Properties();
    props.setProperty(WSConnection.CLIENT_ID, uId);
    props.setProperty(WSConnection.CLIENT_APPLICATION_NAME, appName);
    try {
        Connection nativeConn = new SimpleNativeJdbcExtractor().getNativeConnection(session.connection());
        if (nativeConn instanceof WSConnection) {
            WSConnection wconn = (WSConnection) nativeConn;
            wconn.setClientInformation(props);
        } else {
            logger.error("Connection was NOT an instance of WSConnection so client ID and app could not be set");
        }
    } catch (Exception e) {
        throw new RuntimeException("Cannot set DB parameters!", e);
    }
}

/**
 * Why clear this?  Because we use a connection POOLER and we'd like to clear this info when it is checked into the pool.
 */
private void clearDBProperty() {
    setDBProperty("", "");
}

最佳答案

首先,HibernateTransactionManager.doBegin()方法在这段代码中引发错误:

if (txObject.hasConnectionHolder() &&
!txObject.getConnectionHolder().isSynchronizedWithTransaction()) {
throw new IllegalTransactionStateException(
"Pre-bound JDBC Connection found! HibernateTransactionManager does not support " +
"running within DataSourceTransactionManager if told to manage the DataSource itself. "+
"It is recommended to use a single HibernateTransactionManager for all transactions " +
"on a single DataSource, no matter whether Hibernate or JDBC access.");
}


造成此错误的主要原因是:


为不同的SessionFactory实例(A和B)配置HibernateTransactionManager的两个实例(A和B)–可能使用相同的基础DataSource
然后,A的事务处理方法调用B的事务处理方法,并引发以下消息(在HibernateTransactionManager.doBegin()中进行硬编码)的IllegalTransactionStateException


找到预绑定的JDBC连接!如果告知HibernateTransactionManager管理DataSource本身,则它不支持在DataSourceTransactionManager中运行。无论是Hibernate还是JDBC访问,建议对单个DataSource上的所有事务都使用单个HibernateTransactionManager。

这是配置错误。检查您的整个配置以找出问题所在。

附言:在任何情况下,异常消息都可能引起误解,因为HibernateTransactionManager可能实际上是在不是DataSourceTransactionManager的事务管理器中运行的。

07-25 23:18