使用HibernateCallback进行Spring测试无法正常工作

时间:2012-01-04 08:33:08

标签: java spring

我尝试测试 WriteTxnFinishProcessorTest ,它运行时没有任何异常。 hibernate日志显示它正确回滚,但db字段' LastUpdateTime '仍然更新新值。 为什么? HibernateCallback不在hibernate事务下吗?

日志显示如下:

[main         ] 20120104 15:44:54.284 INFO  HibernateTransactionManager - Using DataSource [com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 5000, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 2sa1nt8k1aivnzwna070g|1a7b0bf, debugUnreturnedConnectionStackTraces -> true, description -> null, driverClass -> com.sybase.jdbc3.jdbc.SybDriver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 2sa1nt8k1aivnzwna070g|1a7b0bf, idleConnectionTestPeriod -> 120, initialPoolSize -> 2, jdbcUrl -> jdbc:sybase:Tds:10.10.10.203:6332/NIAIMM, lastAcquisitionFailureDefaultUser -> null, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 180, maxIdleTimeExcessConnections -> 120, maxPoolSize -> 50, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 2, numHelperThreads -> 3, numThreadsAwaitingCheckoutDefaultUser -> 0, preferredTestQuery -> null, properties -> {user=******, password=******}, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 60, usesTraditionalReflectiveProxies -> false ]] of Hibernate SessionFactory for HibernateTransactionManager
[main         ] 20120104 15:44:54.557 DEBUG AbstractPlatformTransactionManager - Creating new transaction with name [testProcessIn]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
[main         ] 20120104 15:44:54.614 DEBUG HibernateTransactionManager - Opened new Session [org.hibernate.impl.SessionImpl@6af2fb] for Hibernate transaction
[main         ] 20120104 15:44:54.619 DEBUG HibernateTransactionManager - Preparing JDBC Connection of Hibernate Session [org.hibernate.impl.SessionImpl@6af2fb]
[main         ] 20120104 15:44:54.652 DEBUG HibernateTransactionManager - Exposing Hibernate transaction as JDBC transaction [com.mchange.v2.c3p0.impl.NewProxyConnection@11f5ff9]
[main         ] 20120104 15:44:54.668 DEBUG LoggingAspect        - DAO:GenericDAOImpl.executeHQLUpdate
[main         ] 20120104 15:44:54.680 DEBUG LoggingAspect        - args:[update DailyImmigrationsTemp set ImmigRcode='0000', LastUpdateTime=?, TxnMark=0 where EdCardNo=? and Port=? and ImmigrateDate=? and ImmigrateSeq=?, [Ljava.lang.Object;@1267610]
[main         ] 20120104 15:44:55.372 DEBUG SQLStatementLogger   - update DailyImmigrationsTemp set ImmigRcode='0000', LastUpdateTime=?, TxnMark=0 where EdCardNo=? and Port=? and ImmigrateDate=? and ImmigrateSeq=?
[main         ] 20120104 15:44:55.421 WARN  LoggingAspect        - execution  time:740 ms, return:1
[main         ] 20120104 15:44:55.422 DEBUG AbstractPlatformTransactionManager - Initiating transaction rollback
[main         ] 20120104 15:44:55.422 DEBUG HibernateTransactionManager - Rolling back Hibernate transaction on Session [org.hibernate.impl.SessionImpl@6af2fb]
[main         ] 20120104 15:44:55.455 DEBUG HibernateTransactionManager - Closing Hibernate Session [org.hibernate.impl.SessionImpl@6af2fb] after transaction

=== WriteTxnFinishProcessorTest.java ===

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContextTest.xml")
@TransactionConfiguration(transactionManager="txManager",defaultRollback=true)
@Transactional
public class WriteTxnFinishProcessorTest {
    @Autowired 
    private GenericDAO dailyImmigrationsTempDAO;

    @Test
    public void testProcessIn() {
        String  hql="update DailyImmigrationsTemp set LastUpdateTime=? where EdCardNo=? and Port=? and ImmigrateDate=? and ImmigrateSeq=?";
        Object[] params=new Object[]{new Date(),"5550137001",12,"20111214",1};
        int cnt = dailyImmigrationsTempDAO.executeHQLUpdate(hql, params);
        System.out.println("cnt:"+cnt);
    }
}

=== DailyImmigrationsTempDAO.java ===

   :
   :
public int executeHQLUpdate(final String hql, final Object[] params ){
    int ret = (Integer)getHibernateTemplate().execute(new HibernateCallback<Object>() {
        public Object doInHibernate(Session sess) throws HibernateException {
            Query query = sess.createQuery(hql);
            for (int i=0;i<params.length;i++){
              query.setParameter(i, params[i]);  
            }
            return query.executeUpdate();
        }
    });
    return ret;
}

=== applicationContextTest.xml ===

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        :
        : 
    </bean>
    <bean id="abstractDAO" abstract="true">
        <property name="sessionFactory">
            <ref bean="sessionFactory" />
        </property>
    </bean>
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" destroy-method="destroy">
        <property name="dataSource">
            <ref bean="dataSource" />
        </property>
        <property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration" />
        <property name="packagesToScan">
            <list>
                <value>com.pojo</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.SybaseDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <bean id="dailyImmigrationsTempDAO" class="com.dao.GenericDAOImpl" parent="abstractDAO">
        <constructor-arg value="com.pojo.DailyImmigrationsTemp" />
    </bean>
</beans>

1 个答案:

答案 0 :(得分:0)

您似乎没有更改Spring事务测试的默认值,因此@TransactionConfiguration(transactionManager =“txManager”,defaultRollback = true)行似乎没有做任何事情。但是,您正在引用一个名为txManager的bean,它未在您的bean配置文件中声明。来自docs

  

@TransactionConfiguration

     

定义用于配置事务测试的类级元数据。   具体来说,就是PlatformTransactionManager的bean名称   如果用于驱动事务可以显式配置   所需的PlatformTransactionManager的bean名称不是   “transactionManager的”。此外,您可以更改defaultRollback   标志为假。通常,使用@TransactionConfiguration   与@ContextConfiguration合作。

春季测试运行员可能会对您的交易经理感到困惑;由显示的配置创建的隐式命名为'transactionManager'。尝试完全删除该行。另一件事是使用@Transactional显式注释你的executeHQLUpdate()方法。