我被要求爲基於hibernate的數據訪問對象編寫一些編碼測試。爲什麼我的Hibernate插入不反映在我的Hibernate查詢中?
我想我會從一個簡單的測試開始:當我保存模型時,它應該在由dao.getTheList()
返回的集合中。問題是,無論如何,當我撥打dao.getTheList()
時,它總是一個空集合。
應用程序代碼已在生產環境中運行,因此我們假設問題僅出現在我的測試代碼中。
@Test
@Transactional("myTransactionManager")
public void trivialTest() throws Exception {
...
// create the model to insert
...
session.save(model);
session.flush();
final Collection<Model> actual = dao.getTheList();
assertEquals(1, actual.size());
}
測試輸出是expected:<1> but was:<0>
到目前爲止,我已經試過explicitly committing插入後,和disabling the cache,但沒有奏效。
我不想成爲Hibernate的主人,我沒有足夠的時間閱讀整個文檔。如果不知道從哪裏開始,這似乎是對社區來說可能是個好問題。
在測試的驗證步驟執行之前,我可以做些什麼來確保我的Hibernate插入被刷新/提交/解除緩存/或者其他什麼?
一些額外的信息,我已經嘗試過。我試圖手動提交插入並調用dao.getTheList()
之間的交易,但我得到的錯誤Could not roll back Hibernate transaction; nested exception is org.hibernate.TransactionException: Transaction not successfully started
@Test
@Transactional("myTransactionManager")
public void trivialTest() throws Exception {
...
// create the model to insert
...
final Transaction firstTransaction = session.beginTransaction();
session.save(model);
session.flush();
firstTransaction.commit();
final Transaction secondTransaction = session.beginTransaction();
final Collection<SystemConfiguration> actual = dao.getTheList();
secondTransaction.commit();
assertEquals(1, actual.size());
}
我也試着打破服用@Transactional
註釋時,將測試線和註釋每2種輔助方法,每個Hibernate作業一個。爲此,雖然我得到錯誤:No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
。
[/編輯]
有什麼在dao.getTheList(); – Ashish451
這是一個空集合 – ds390s