我正在使用 Spring 3,我使用 Hibernate3 作为 O/R 映射器。在测试我的 DAO 类时,我打算将我的测试类声明为@Transactional,以便我可以回滚数据库中的内容。DAO 类工作正常,但是回滚永远不会发生。这就是我的测试类的样子:
@BeforeTransaction
public void createTestData() {
// instantiate User objects
}
@Before
public void insertTestData() {
jdbcTemplate.update("INSERT INTO USER VALUES" + user1);
jdbcTemplate.update("INSERT INTO USER VALUES" + user2);
jdbcTemplate.update("INSERT INTO USER VALUES" + user3);
}
@Test
@Rollback(true)
public void testCheckAvailability() {
boolean trueResult = userDao.checkAvailability("shaaadi");
boolean falseResult = userDao.checkAvailability("elthefar");
assertEquals("Invalid output", true, trueResult);
assertEquals("Invalid output", false, falseResult);
}
}
不要忘记 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"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>/database.properties</value>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"><value>${jdbc.driverClassName}</value></property>
<property name="url"><value>${jdbc.url}</value></property>
<property name="username"><value>${jdbc.username}</value></property>
<property name="password"><value>${jdbc.password}</value></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
p:dataSource-ref="dataSource">
<property name="annotatedClasses">
<list>
<value>ir.cms.domain.user.User</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.format_sql=true
hibernate.dialect=org.hibernate.dialect.MySQLDialect
</value>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory" />
<bean id="userDao"
class="ir.cms.dao.user.impl.UserDaoImpl"
p:sessionFactory-ref="sessionFactory" />
</beans>
最后,我应该补充一点,DAO 类不是事务性的,仅被注释为 @Repository。我很感激任何建议:)