我试图在使用Spring-test时没有成功的情况下获取JDBC事务回滚。当我运行以下时,SQL更新始终被提交。Spring JDBC测试上的事务回滚
package my.dao.impl;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.transaction.TransactionConfiguration;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.Statement;
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class})
@ContextConfiguration(locations={"classpath:ApplicationContext-test-DAOs.xml"})
@TransactionConfiguration(defaultRollback = true)
public class ConfirmationMatchingDAOImplTest {
@Autowired
private DataSource dataSource;
@Test
public void shouldInsertSomething() throws Exception {
final Connection connection = dataSource.getConnection();
final Statement statement = connection.createStatement();
statement.executeUpdate("insert into TEST_INSERT values (1, 'hello')");
statement.close();
connection.close();
}
}
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="url" value="jdbc:sqlserver://makeitfunky:1490;databaseName=fonzie"/>
<property name="username" value="ralph"/>
<property name="password" value="p0n1es_R_kew1"/>
</bean>
我在做什么错?
此外,我是否使用了太多注释?我可以让它更清洁一点吗?
我删除了@TestExecutionListeners并添加了@Transactional。然后我必须添加一个transactionManager bean到应用程序上下文(DataSourceTransactionManager)。 Txn没有回滚,所以我添加了@TransactionConfiguration(defaultRollback = true)。 Txn仍然没有回滚,所以我在测试方法中添加了@Rollback。只有那时我才看到Spring日志回滚了txn,但更新仍然持续到数据库。可能与SQL Server及其驱动程序有关? – Synesso 2010-10-29 02:21:43
添加DataSourceUtils到我的答案。 – 2010-10-29 02:35:09
啊,我没有得到你最后的评论通知。在此期间,我改变了我的上下文以将数据源包装在TransactionAwareDataSourceProxy中。这工作。所以你去了,有两种方法来做同样的事情。现在看看我可以摆脱这7个注释中的哪一个,并且仍然有效。 – Synesso 2010-10-29 03:41:31