简体   繁体   中英

ejb3 isolated (autonomous) transaction inside session bean

I'm using XA (2-phase) transaction. I want to log to one log-table through Log class and Entity Manager. My method inside EJB Session bean looks like:

private void logError(Throwable throwable) {
    LogEntity logEntity = new LogEntity();
    // Set everything
    entityManager.persist(logEntity);
}

I want to it in isolated (autonomous) transaction independent of any "outer" transaction. I have already tried to add @TransactionAttribute(value = TransactionAttributeType.REQUIRES_NEW) and @TransactionAttribute(value = TransactionAttributeType.NOT_SUPPORTED) before method name and does not work.

Before I call EJB3 method I create user transaction like:

try {
    UserTransaction transaction = (UserTransaction)context.lookup("javax.transaction.UserTransaction");
    transaction.begin();
    // Call EJB3 method
    transaction.commit();
} catch (Throwable t) {
    t.printStackTrace();
    try {
        transaction.rollback();
    } catch (SystemException e) {
        e.printStackTrace();
    }
}

I want to Log no matter if commit is done or not. How to?

Regards

Transaction attributes are only relevant when called through a proxy. They do not apply to direct calls, which includes private methods. Try something like the following (which uses EJB 3.1 no-interface view, though you could create a separate local interface for logging if you only have EJB 3.0):

@Stateless
@Local(BusinessInterface.class)
@LocalBean
public class MyBean {
  @EJB MyBean logger;

  @TransactionAttribute(REQUIRED)
  public void businessMethod() {
    try {
      ...
    } catch (Throwable t) {
      logger.logError(t);
      ...
    }
  }

  @TransactionAttribute(NOT_SUPPORTED)
  public void logError(Throwable t) {
    ...
  }
}

The important piece is that the call to logError happens through an injected EJB proxy, which allows the container to have control to suspend the XA transaction for the duration of the logError method.

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