Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to roll back JTA transaction correctly?

What is the correct way of rolling back the transaction of a container managed JTA transaction?

I understand this: EJBException when calling entityManager.getTransaction() that I can't get the transaction instance. I read a solution here but I'm not sure whether this is correct.

I'm also aware that, if I throw an exception, the transaction will be rolled back.

But my question is: if I want to (must) use a container managed EntityManager, what's the correct way of rolling back a transaction inside it?

like image 225
szegedi Avatar asked Feb 04 '13 11:02

szegedi


People also ask

What is JPA and JTA?

JPA (Java Persistence API) is the Java ORM standard/specification for storing, accessing, and managing Java objects in a relational database. Hibernate is an implementation of the Java Persistence API (JPA) specification. JTA (Java Transaction API) is the Java standard/specification for distributed transactions.

Does spring use JTA?

Spring Boot supports distributed JTA transactions across multiple XA resources by using either an Atomikos or Bitronix embedded transaction manager. JTA transactions are also supported when deploying to a suitable Java EE Application Server.


1 Answers

The asnwer on Code Ranch is right, you have to use SessionContext

@Resource
private SessionContext ctx;

//and then in method
if(fail) {
    ctx.setRollBackOnly(); 
}

See also this article.

like image 181
Petr Mensik Avatar answered Nov 03 '22 01:11

Petr Mensik