0

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();
}
Vineet Reynolds
  • 76,006
  • 17
  • 150
  • 174
Muhammad Hewedy
  • 29,102
  • 44
  • 127
  • 219

2 Answers2

6

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.

Vineet Reynolds
  • 76,006
  • 17
  • 150
  • 174
  • What do you mean by "still don't work"? Does transaction creation fail on every invocation or something else? Also, consider enabling finer debugging of the JTA co-ordinator; you will be able to determine whether a new transaction is being started or not. – Vineet Reynolds Jun 26 '11 at 14:10
  • I mean, the database don't get updated on each exit of `saveObj` however, in the app server log, the update sql query got printed – Muhammad Hewedy Jun 26 '11 at 14:53
  • What JPA provider are you using? If you are using EclipseLink, have you integrated the provider with the [JTA transaction manager of OC4J](http://wiki.eclipse.org/Integrating_EclipseLink_with_an_Application_Server_(ELUG)#Integrating_EclipseLink_with_Oracle_Containers_for_J2EE_.28OC4J.29)? – Vineet Reynolds Jun 26 '11 at 15:20
  • I am using oc4j 10.1.3.4 as EJB container and its bundled toplink as JPA implementation. – Muhammad Hewedy Jun 26 '11 at 19:50
  • I can think of one possible reason - is there a `ejb-jar.xml` or `orion-ejb-jar.xml` file whose entries would override the annotation? Usually, the container uses the attributes declared in the annotations, unless there is a deployment descriptor that describes the values. In the event of a conflict, the values in the deployment descriptor take precedence. – Vineet Reynolds Jun 26 '11 at 21:10
1

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

fvu
  • 32,488
  • 6
  • 61
  • 79