我不能在我的 TestCase 中使用 @Transactional 注释。我有解决方法 - 直接使用 TransactionalManager。不幸的是,当我基于 SpringContext 中的 DataSource 在 groovy 中创建 Sql 对象然后向数据库中插入一行时,它不会回滚。
@ContextConfiguration(locations = [ "../dao/impl/ibatis/spring-data-context-config.xml"])
@RunWith(SpringJUnit4ClassRunner.class)
public class OrganizationTest {
@Autowired
DataSource dataSource;
@Autowired
DataSourceTransactionManager transactionManager;
private TransactionStatus transactionStatus;
@Before
public void setUp() {
transactionStatus = transactionManager.getTransaction(new DefaultTransactionDefinition());
}
@After
public void tearDown() {
transactionManager.rollback(transactionStatus);
transactionStatus = null;
}
@Test
public void shallObtainSequenceNo() throws Exception {
Connection connection = dataSource.getConnection();
connection.setAutoCommit(false);
Sql sql = new Sql(dataSource);
//given
Organization organization = new Organization("KongregatzionIX", "bisut000000000000001");
//when
organization.insert(sql);
//then
assertNotNull(organization.getId());
}
}
SQL 查询如下所示:
public class Organization {
String name;
String id;
String parentId;
Organization(String name, String parentId){
this.name = name;
this.parentId = parentId;
}
public void insert(Sql sql){
String createdBy = GlobalConstant.SABA_ADMIN_ID.getValue();
String updatedBy = GlobalConstant.SABA_ADMIN_ID.getValue();
String companyType = "2";
String flags = "1000000000";
id = sql.firstRow( "select 'bisut' || LPAD(TPT_COMPANY_SEQ.NEXTVAL, 15, '0') as id from dual ").id;
def timeStamp = sql.firstRow("select to_char(SYSTIMESTAMP, 'YYYYMMDDHH24MISSFF') as ts FROM DUAL ").ts;
def nameIns = name;
def today = new java.sql.Date(new Date().getTime());
sql.executeInsert('''
INSERT INTO TPT_COMPANY(ID, TIME_STAMP, CREATED_BY, CREATED_ON, UPDATED_BY, UPDATED_ON, CI_NAME, NAME, CI_NAME2, NAME2, COMPANY_TYPE, FLAGS, PARENT_ID)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)
''' ,
[id, timeStamp, createdBy, today, updatedBy, today, nameIns.toLowerCase(), nameIns, nameIns.toLowerCase(), nameIns, companyType, flags, parentId]);
}
}
当然,我想设置跨越所有测试方法的事务。
// 编辑
由于声誉太小,我无法回答,但 TransactionAwareDataSourceProxy 是我一直在寻找的。