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?
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.
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:
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!