java - Micronaut 和 JUnit 回滚
问题描述
我为 micronaut 微服务编写了一些测试。我希望在我的测试完成后,数据库中的所有更改都被还原(回滚)。首先,我写了一个似乎可行的简单示例。更改被还原。但是当我使用相同的类比运行微服务测试时,更改不会恢复。
简单的工作示例:
@Test
@Transactional
public void testRollback() {
try (Connection connection = dataSource.getConnection();
Statement stmt = connection.createStatement()){
connection.setAutoCommit(false);
stmt.execute(String.format("INSERT INTO city VALUES (9999, 'Darko town', '123')"));
connection.rollback();
} catch (SQLException e) {
Assert.fail("Exception " + e);
}
}
执行此操作后,城市将从数据库中删除。
我的真实测试场景:
@Test
@Transactional
public void testDeleteDocuments() {
try (final Connection connection = deletionService.getDataSource().getConnection();
Statement stmt = connection.createStatement()) {
connection.setAutoCommit(false);
deletionService.startHacDeletion();
connection.rollback();
}catch (SQLException e) {
Assert.fail("Exception " + e);
}
}
通过我正在测试的方法完成的所有操作:DeletionService.startHacDeletion()
都不会还原。
我错过了什么吗?这是正确的方法吗?请协助....
更新:
这是删除功能
public void deleteHacDocuments () {
List<Document> allComments = new ArrayList<>();
while (hacDeletionActive) {
List<Document> parentDocuments = documentRepository.findHacDocuments();
LOG.info(String.format("Remove HAC parent documents %d", parentDocuments.size()));
for(Document document : parentDocuments){
LOG.info(String.format("Remove HAC documents %d", document.getId()));
}
if (parentDocuments.isEmpty()) {
hacDeletionActive = false;
LOG.info("HAC deletion finished");
} else {
for (Document doc : parentDocuments) {
if (doc.getType() == 1) {
deleteWholeStudy(doc.getId());
} else if (doc.getType() == 6) {
List<Document> studies = documentRepository.findStudiesByCase(doc.getId());
for (Document study : studies) {
deleteWholeStudy(study.getId());
}
deleteWholeCase(doc.getId());
} else if (doc.getType() == 4) {
allComments.add(doc);
} else {
documentService.markDocumentAsDeleted(doc.getId());
}
}
documentService.markCommentsAsDeleted(allComments);
}
}
}
解决方案
我对 Micronaut 框架不是很熟悉,也不太明白@Transactional
如果手动回滚更改,为什么需要注释。
但是从您的示例中可以明显看出,在第一种情况下,您使用 aconnection
创建一个statement
用于执行查询的,然后在相同的connection
. 在第二种情况下,您connection
从 中获得一个DataSource
,但您没有将它传递给服务以使用它,因此如果DataSource
使用某个连接池并且并不总是返回相同的连接,则服务connection
将从它获得另一个,而不是那个你正在回滚。
这是我在您的代码中看到的唯一可能的问题,如果我的回答不能帮助解决您的问题,请提供一个最小的、可重现的示例。
推荐阅读
- c++11 - 通过 switch-case 梯形图调用 write 时无法以二进制模式写入文件
- javascript - 用静态和动态值创建数组组合的最佳方法是什么
- pyspark - pyspark 2.0中按箭头键时的字符“^[[A”“^[[B”“^[[C”“^[[D”
- flutter - 颤振选项卡没有正确下划线
- c# - VB.NET Azure Functions — Microsoft.CSharp 程序集有什么作用?
- ios - 如何使用 if 逻辑或三元运算符在 Swift 中设置枚举案例的 rawValue?
- java - 如何在java中自动填充对象?
- python - 为什么在笛卡尔坐标和球坐标之间转换时,这个python代码给出了错误的答案?
- tfs - 如何为空白日期制定 TFS 样式规则
- c# - 如何在选择方法中使用实例名称为类实例成员赋值