2010-11-04 51 views
0
 

@Transactional 
public void start() { 
    ... 
    ... 
    int result = entityManager 
       .createQuery("update Users set name=" + value + " where user.id=5").executeUpdate(); 
    ..... 

} 
 

上面的代碼給出了javax.persistence.TransactionRequiredException異常。在交易中間更新數據庫,可能嗎?

在交易中間更新數據庫,可能嗎?

有什麼建議嗎?

謝謝。

A.

我只是想知道

回答

4

這是由持久性提供拋出當需要事務,但不活躍運行時異常。交易是必需的,因爲start方法被註釋爲交易。爲了消除例外情況,您必須調查爲什麼該行被稱爲不在事務上下文中。

數據庫更新可能在(不同的)事務期間是可能的。取決於由活動事務和事務策略鎖定的表。但在這種情況下,您看起來像您需要激活交易之前您輸入start方法。


隨着JPA你會做這樣的事情:

em = emf.createEntityManager(); 
tx = em.getTransaction(); 
tx.begin(); // now a transaction is active 
start();  // call your method 
// call other methods... 
tx.commit(); // now the update is actually done 
em.close(); 

注意 - 這是接近僞代碼,異常處理缺少在這個例子。

+0

怎麼樣?一個例子,請...謝謝。 – Altug 2010-11-04 08:19:48