2013-08-16 42 views
1

後,我有一個Containter管理交易 - 豆是這樣的:javax.persistence.TransactionRequiredException使用setRollbackOnly

@PersistenceContext 
    private EntityManager em; 

    @Resource 
    private EJBContext ejbContext; 


    public void testTransaction() { 
    Model model1 = new Model(); 
    em.persist(model1); 

    ejbContext.setRollbackOnly(); 

    Model model2 = new Model(); 
    em.persist(model2);//the line the problem 
    } 

在最後一行(有問題的)一個TransactionRequiredException拋出:

javax.ejb.EJBException: javax.persistence.TransactionRequiredException: JBAS011469: Transaction is required to perform this operation (either use a transaction or extended persistence context) 

但是在Mastering EJB 4th edition書中(搜索「Doomed Transactions」或者轉到第299頁),它是這樣解釋的,因爲它不會被拋出任何這樣的例外,而應該在資源飢渴的操作之前檢查ejbContext.getRollbackOnly()

當然,我可以在這個簡單的例子中通過拋出一個帶有@ApplicationException(rollback=true)註解的異常來避免這個問題,但我只是想知道我錯過了什麼。

回答

0

通過調用ejbContext.setRollbackOnly(),您已終止由容器啓動的當前事務。之後,沒有可以與em.persist(model2);相關聯的事務。所以你會得到一個異常。 要檢查事務是否處於活動狀態,請在ejbcontext中使用getRollbackOnly()方法,該方法將返回false。

+1

嗯,這是我的情況的唯一解釋,但在'setRollBackOnly()'的文檔中,沒有寫關於當前事務的未分配(並且在EJB 3.1規範中都沒有)http:// docs .oracle.com/javaee/6/api/javax/ejb/EJBContext.html#setRollbackOnly%28%29所以我可以說這是一個BUG。我在Jboss 7.1.1中試了一下。你用什麼AS來試試? –

相關問題