2017-07-25 123 views
0

我被要求爲基於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

[/編輯]

+0

有什麼在dao.getTheList(); – Ashish451

+0

這是一個空集合 – ds390s

回答

0

我覺得只要底層DBMS可能隱藏的變化對其他事務的改變交易尚未完成。 getTheList是否在額外的事務中運行?你使用的是oracle還是postgres?

+0

這是H2內存數據庫。我傾向於同意,這與交易有關。儘管如此,交易是由測試方法上的註釋驅動的。我試過手動提交事務,但它只是錯誤。我會擴展我的問題,包括我已經完成的測試。 – ds390s

+0

ejb中不允許使用聲明式和明確式事務管理的組合。所以我不知道該怎麼做。但也許:https://stackoverflow.com/questions/24338150/how-to-manually-force-a-commit-in-a-transactional-method可以幫助嗎?或者,您可以將插入內容封裝到使用「REQUIRES_NEW」完成的方法中。或者,最後,dao中的查詢無法正常工作。 – aschoerk