8

I am new to the EJB Projects. And am trying to understand the usage of @Transactional annotation at top of my EJB methods. I have searched for the content and there is no clear explanation on this. Can anyone explain clearly about this.

Arun
  • 609
  • 2
  • 12
  • 33

1 Answers1

10

@Transactional comes from the Spring world, but Oracle finally included it in Java EE 7 specification (docs). Previously, you could only annotate EJBs with @TransactionAttribute annotation, and similar is now possible for CDIs as well, with @Transactional. What's the purpose of these annotations? It is a signal to the application server that certain class or method is transactional, indicating also how it is gonna behave in certain conditions, e.g. what if it's called inside a transaction etc.

An example:

@Transactional(Transactional.TxType.MANDATORY)
public void methodThatRequiresTransaction()
{
..
}

The method above will throw an exception if it is not called within a transaction.

@Transactional(Transactional.TxType.REQUIRES_NEW)
public void methodThatWillStartNewTransaction()
{
..
}

Interceptor will begin a new JTA transaction for the execution of this method, regardless whether it is called inside a running transaction or not. However, if it is called inside a transaction, that transaction will be suspended during the execution of this method.

See also:

Miljen Mikic
  • 14,765
  • 8
  • 58
  • 66
  • Yes I got It. So here what is the difference between calling inside transaction context and outside the context? – Arun Apr 20 '15 at 09:16
  • 2
    @Arun When you are writing a method, you usually cannot anticipate how it will be used in the business scenario. One client may start its own transaction and then invoke your method, other maybe doesn't use transactions at all. By specifying appropriate Transactional.TxType, you are the one who controls the execution of your method depending on the transaction context. For example, if everything you do in your method needs to be in one transaction and you don't care if it is called from the transaction context or not, then use `@Transactional(Transactional.TxType.REQUIRED)` – Miljen Mikic Apr 20 '15 at 10:27
  • That's Informative. I understood the use of Transactional attribute here. When i run throw my code i have found @Transactional annotation at few methods of my EJB classes and it is uses class from package `weblogic.jws.Transactional`. My EJB class is exposed as Webservice. Am just confused between the two. – Arun Apr 20 '15 at 12:16
  • @Arun The annotation that you are referring to is Weblogic-specific. According to the documentation (http://docs.oracle.com/cd/E13222_01/wls/docs90/webserv/annotations.html#1057803), it just determines if some method is transactional or not, without additional properties available in the annotation I mentioned in my answer. – Miljen Mikic Apr 20 '15 at 12:22