how to commit a transaction in EJB?

余生颓废 提交于 2019-12-23 05:47:11

问题


I have the following scenario,

public void someEjbMethod1()
{
    for (int i=0; i=10; i++)
    {
        em.merge(arr[i]);
        em.flush();
    }
}

I need to merge each object of (arr[i]) separately. as the above code will commit all the arr[i] instances at the end of the function.

I am thinking to do the following:

public void someEjbMethod1()
{
    for (int i=0; i=10; i++)
    {
        saveObj(arr[i]);
    }
}

// should I use a transaction attribute here??
public void saveObj(SomeObject obj)
{
    em.merge(arr[i]);
    em.flush();
}

回答1:


If you want container managed transactions, you may use the @TransactionAttribute with the value TransactionAttributeType.REQUIRES_NEW to annotate the saveObj method as:

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void saveObj(SomeObject obj)
{
    ...
}

This will ensure that a new transaction will be started for every invocation of the saveObj method. The existing transaction associated with the someEjbMethod will be suspended before every invocation of the saveObj method. Every transaction started for the saveObj method will be committed on return, and hence every entity will be updated in the database in it's own transaction.




回答2:


You can request a UserTransaction, have a look here for some inspiration.



来源:https://stackoverflow.com/questions/6483812/how-to-commit-a-transaction-in-ejb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!