Question

I'm experimenting with JTA transactions and can't understand why a method that's marked to always create a new transaction doesn't (code edited to relevant stuff). This is a re-work of a previous question I asked on a similar topic (here):

@Stateless
public class StaffEntityOps
{
  @Resource TransactionSynchronizationRegistry txReg;

  private void transactionStatus(String where)
  {
    String msg;
    int stat = txReg.getTransactionStatus();
    switch (stat) {
      case STATUS_ACTIVE:
        msg = "Active";
        break;
      case STATUS_NO_TRANSACTION:
        msg = "No Transaction";
        break;
      default:
        msg = "Other: " + stat;
    }
    System.out.println("Transaction status in " + where + ": " + msg);
  }

  @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
  private void saveToEM(EntityManager em, StaffEntity staffEntity)
      throws ...
  {
    transactionStatus("saveToEM: ");
    em.persist(staffEntity);
    em.flush();
  }

  @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
  public void add(StaffEntity staffEntity)
      throws ...
  {
    // Entity Managers emDB1 and emDB2 are injected into class.
    transactionStatus("add: ");
    saveToEM(emDB1, staffEntity);
    saveToEM(emDB2, staffEntity);
  }

The idea above, was to call the add(StaffEntity staffEntity) method to persist a new StaffEntity to a set of non-XA DataSources. I've solved this using bean-managed transactions (previous question, cited above), and also with XA-DataSources. I'd still like to determine if there's a way to do it with container-managed transactions and non-XA DataSources (primarily to understand how the @TransactionAttribute annotation affects things).

The attempt above is trying to explicitly create a new transaction for the persist to each database by isolating the persist in its own method, and marking it with REQUIRES_NEW. This isn't working -- The sysout messages indicate that in both add and saveToEM methods, there is "No Transaction".

Why isn't a new transaction being created for each invocation of saveToEM? It makes sense to me that the add method has "No Transaction" because it is marked NOT_SUPPORTED. But shouldn't the REQUIRES_NEW on saveToEM cause a new transaction to be created each time it is called? (Glassfish 4.0, EclipseLink 2.5)

Was it helpful?

Solution

Because saveToEM is being called locally, it is treated as just a java method, so the container will not start a transaction for the call.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top