[英]Don't understand behavior of nested transactions in Spring
我的數據庫有觸發器。 它們在創建實體后觸發。 我想測試一個條件,該條件取決於觸發器執行的結果。 因此,我需要能夠在測試中看到那些結果。 但是觸發器將在提交后觸發,而該事務實際上將被回滾。
看來,我需要使用transactionTemplate
和PROPAGATION_REQUIRES_NEW
創建一個新事務。 我嘗試過這種方式,並且能夠看到觸發器執行的結果(糟糕!)。 但是這種方式帶來了另一個問題:看一下代碼,我試圖通過注釋來解釋一個奇怪的行為。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestConfiguration.class})
@Transactional
public class ServiceTest {
@Inject
private PlatformTransactionManager txManager;
<...>
@Before
public final void setUp() {
clearDatabase();
}
@Test
public final void testFilter() {
// Note: here database is empty - was cleared by setUp() method
TransactionTemplate tt = new TransactionTemplate(txManager);
tt.setPropagationBehavior(PROPAGATION_REQUIRES_NEW);
tt.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus s) {
createAndSaveEntity();
}
});
// Here I can see created entity and results of the trigger execution
// But also I see all entities, which was in the database before setUp()
// That is very strange! Why they appear if I deleted them?
<...>
}
}
PS:我使用Spring Data Neo4j 4.0.0.RELEASE和Neo4j 2.3.1
Neo4j不支持嵌套事務。 因此,如果事務事件處理程序(我認為您(正確地)稱為“觸發器”)豐富了事務,則它需要在beforeCommit()
,它將參與“全有或全無”操作。 最好的測試選擇是讓事務在每次測試之前或之后提交,聲明需要聲明的內容並清除數據庫。
(如果您確實在針對遠程數據庫運行,則GraphAware RestTest可能有助於斷言和清除。如果您使用嵌入式模式進行測試,請使用GraphUnit 。)
您的問題實際上有所不同。 在測試運行之間似乎沒有清除某些內容(例如SDN Session
)。 要么明確清除它,要么用@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
注釋測試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.