how to commit a transaction in EJB?
I have the following scenario,
public vo开发者_如何学JAVAid 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.
You can request a UserTransaction, have a look here for some inspiration.
精彩评论