javax.transaction.Transactional vs org.springframework.transaction.annotation.Transactional

Spring has defined its own Transactional annotation to make Spring bean methods transactional, years ago.

Java EE 7 has finally done the same thing and now allows CDI bean methods to be transactional, in addition to EJB methods. So since Java EE 7, it also defines its own Transactional annotation (it obviously can't reuse the Spring one).

In a Java EE 7 application, you'll use the Java EE annotation.

In a Spring application, you'll use the Spring annotation.

Their use is the same: informing the container (Java EE or Spring) that a method is transactional.


Another difference is how Spring handles the @Transactional annotations

  • org.springframework.transaction.annotation.Transactional is always taken into account
  • javax.transaction.Transactional is taken into account only when EJB3 transactions are present. EJB3 transactions' presence is done by checking if class javax.ejb.TransactionAttribute is available in the classpath (from version 2.5.3 to 3.2.5). Thus you can end up with your annotations not being taken into account if only javax.transaction.Transactional is in your classpath and not javax.ejb.TransactionAttribute. This can be the case if you're working with Hibernate: hibernate-core (4.3.7.Final) depends on jboss-transaction-api_1.2_spec (1.0.0.Final), which doesn't provide javax.ejb.TransactionAttribute.

Please be careful, (this issue happened in tomcat),

If your application is SPRING web application and you are using Spring's transaction handling mechanism that is @org.springframework.transaction.annotation.Transactional, then don't mix it with javax.transaction.Transactional.

That is Always use, @org.springframework.transaction.annotation.Transactional in a spring application consistently.

Otherwise we may end up with this error,

org.springframework.orm.jpa.JpaSystemException: commit failed; nested exception is org.hibernate.TransactionException: commit failed

........

Caused by: java.sql.SQLException: Protocol violation: [0]