简体   繁体   中英

how to commit a transaction in EJB?

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();
}

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.

您可以请求UserTransaction, 在此处查找一些灵感。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM