Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of @Transactional annotation

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.

like image 636
Arun Avatar asked Apr 20 '15 07:04

Arun


People also ask

What is @transactional annotation in Java?

Transactional annotation provides the application the ability to declaratively control transaction boundaries on CDI managed beans, as well as classes defined as managed beans by the Java EE specification, at both the class and method level where method level annotations override those at the class level.

What does @transactional does in Spring?

The @Transactional annotation is metadata that specifies that an interface, class, or method must have transactional semantics; for example, "start a brand new read-only transaction when this method is invoked, suspending any existing transaction".

Is @transactional required?

@Transactional(MANDATORY) : fails if no transaction was started ; works within the existing transaction otherwise. @Transactional(SUPPORTS) : if a transaction was started, joins it ; otherwise works with no transaction.

Where does the @transactional annotation belong?

The @Transactional annotation belongs to the Service layer because it is the Service layer's responsibility to define the transaction boundaries.


1 Answers

@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:

  • TransactionalTxType
like image 136
Miljen Mikic Avatar answered Oct 30 '22 12:10

Miljen Mikic