Prevent transaction rollback in JBoss + Hibernate
Asked Answered
K

2

8

We have a Java application running on JBoss 5.1 and in some cases we need to prevent a transaction from being closed in case a JDBCException is thrown by some underlying method.

We have an EJB method that looks like the following one

@PersistenceContext(unitName = "bar")
public EntityManager em;

public Object foo() {
  try {
    insert(stuff);
    return stuff;
  } (catch PersistenceException p) {
    Object t = load(id);
    if (t != null) {
      find(t);
      return t;
    }
  }
}

If insert fails because of a PersistenceException (which wraps a JDBCException caused by a constraint violation), we want to continue execution with load within the same transaction.

We are unable to do it right now because the transaction is closed by the container. Here's what we see in the logs:

org.hibernate.exception.GenericJDBCException: Cannot open connection
javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Cannot open connection
    at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:614)

   ...

Caused by: javax.resource.ResourceException: Transaction is not active: tx=TransactionImple < ac, BasicAction: 7f000101:85fe:4f04679d:182 status: ActionStatus.ABORT_ONLY >

The EJB class is marked with the following annotations

@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)

Is there any proper way to prevent the transaction from rolling back in just this specific case?

Kunlun answered 4/1, 2012 at 16:52 Comment(0)
V
5

You really should not try to do that. As mentioned in another answer, and quoting Hibernate Docs, no exception thrown by Hibernate should be treated as recoverable. This could lead you to some hard to find/debug problems, specially with hibernate automatic dirty checking.

A clean way to solve this problem is to check for those constraints before inserting the object. Use a query for checking if a database constraint is being violated.

public Object foo() {
    if (!objectExists()) {
        insertStuff();
        return stuff();
    }
    // Code for loading object...
}

I know this seems a little painful, but that's the only way you'll know for sure which constraint was violated (you can't get that information from Hibernate exceptions). I believe this is the cleanest solution (safest, at least).


If you still want to recover from the exception, you'd have to make some modifications to your code.

As mentioned, you could manage the transactions manually, but I don't recommend that. The JTA API is really cumbersome. Besides, if you use Bean Managed Transaction (BMT), you'd have to manually create the transactions for every method in your EJB, it's all or nothing.

On the other side, you could refactor your methods so the container would use a different transaction for your query. Something like this:

@Stateless
public class Foo {
    ...
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public Object foo() {
        try {
            entityManager.insert(stuff);
            return stuff;
        } catch (PersistenceException e) {
            if (e.getCause() instanceof ConstraintViolationException) {
                // At this point the transaction has been rolled-backed.
                // Return null or use some other way to indicate a constrain
                // violation
                return null;
            }
            throw e;
        }
    }

    // Method extracted from foo() for loading the object.
    public Object load() {
        ...
    }
}

// On another EJB
@EJB
private Foo fooBean;

public Object doSomething() {
    Object foo = fooBean.insert();
    if (foo == null) {
        return fooBean.load();
    }

    return foo;
}

When you call foo(), the current transaction (T1) will be suspended and the container will create a new one (T2). When the error occurs, T2 will be rolled-backed, and T1 will be restored. When load() is called, it will use T1 (which is still active).

Hope this helps!

Valorous answered 6/1, 2012 at 16:22 Comment(0)
E
2

I don't think it's possible.

In may depend on your JPA provider, but, for example, Hibernate explicitly states that any exception leaves session in inconsistent state and thus shouldn't be treated as recoverable (13.2.3. Exception handling).

I guess the best thing you can do is to disable automatic transaction management for this method and create a new transaction after exception manually (using UserTransaction, as far as I remember).

Eboh answered 4/1, 2012 at 17:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.