2010-10-28 68 views
6

我正在編寫集成測試,並且在一種測試方法中,我想將一些數據寫入數據庫然後讀取它。在春季設置休眠會話的刷新模式

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = {"classpath:applicationContext.xml"}) 
@TransactionConfiguration() 
@Transactional 
public class SimpleIntegrationTest { 

    @Resource 
    private DummyDAO dummyDAO; 

    /** 
    * Tries to store {@link com.example.server.entity.DummyEntity}. 
    */ 
    @Test 
    public void testPersistTestEntity() { 
     int countBefore = dummyDAO.findAll().size(); 
     DummyEntity dummyEntity = new DummyEntity(); 
     dummyDAO.makePersistent(dummyEntity); 

     //HERE SHOULD COME SESSION.FLUSH() 

     int countAfter = dummyDAO.findAll().size(); 

     assertEquals(countBefore + 1, countAfter); 
    } 
} 

正如你可以存儲和讀取數據之間看到,會議應被刷新,因爲默認FushModeAUTO因此沒有數據可以實際存儲在數據庫中。

問題:我可以一些如何設置FlushMode在會話工廠ALWAYS或其他地方,以避免重複session.flush()電話嗎?

DAO中的所有數據庫調用均使用HibernateTemplate實例。

在此先感謝。

+1

你可以讓Spring將'SessionFactory'注入到測試中,並在'setUp'中獲取當前的'Session'並調用'setFlushMode()'嗎? – 2010-10-28 23:59:48

回答

0

這應該是足夠了:

@ContextConfiguration(locations="classpath:applicationContext.xml") 
public class SimpleIntegrationTest extends AbstractTransactionalJUnit4SpringContextTests { 

    @Autowired(required = true) 
    private DummyDAO dummyDAO; 

    @Test 
    public void testPersistTestEntity() { 
     assertEquals(0, dummyDAO.findAll().size()); 
     dummyDAO.makePersistent(new DummyEntity()); 
     assertEquals(1, dummyDAO.findAll().size()); 
    } 
} 

從applicationContext.xml中

<bean id="transactionManager" class="org.springframework.orm.hibernate.HibernateTransactionManager"> 
    <property name="sessionFactory"> 
     <ref bean="sessionFactory"/> 
    </property> 
</bean> 

觀的TransactionalTestExecutionListener的來源,如果您有任何關於交易在這種情況下如何工作的問題。

您也可以使用AOP (aspect oriented programming)來代理交易。

+0

對不起,足夠了嗎?我真的不明白這是如何解決存儲對象後刷新休眠會話的問題。 – glaz666 2010-10-29 09:47:45

+0

雖然您已註釋爲事務性,但實際上並未處理任何事務。看看TransactionalTestExecutionListener類。有一個可以打開事務的beforeTestMethod和一個關閉/回滾的afterTestMethod。 – hisdrewness 2010-10-29 17:31:52

+0

我看了一下TransactionalTestExecutionListener類。它的文檔清楚地表明,使用@Transactional註解的類將啓動並完成方法執行周圍的事務,並且如果還使用@TransactionConfiguration對類進行註釋,則它將回滾。你提到的方法是「......能夠執行特定的設置或拆除事務之外的代碼」。所以我猜,事實上根據需要進行處理 – glaz666 2010-11-03 13:45:47

1

嘗試添加以下內容:

@Autowired 
private SessionFactory sessionFactory; 

@Before 
public void myInitMethod(){ 
    sessionFactory.getCurrentSession().setFlushMode(FlushMode.ALWAYS); 
} 
1

hibernate object flushing,沖洗在以下幾點默認會:

  • 在某些查詢執行
  • 從org.hibernate.Transaction.commit ()
  • from Session.flush()

因此,在調用dummyDAO.findAll().size();之前,會話中的對象已經在db中刷新。設置FlushMode總是沒有必要。