I\'m learning about how to create REST API with JPA and Hibernate and a MySQL database and I see this @Transactional annotation. Can someone explain what is the use of this anno
@Transactional
annotation is used when you want the certain method/class(=all methods inside) to be executed in a transaction.
Let's assume user A
wants to transfer 100$ to user B
. What happens is:
Let's assume the exception is thrown after succeeding 1)
and before executing 2)
. Now we would have some kind of inconsistency because A
lost 100$ while B
got nothing.
Transactions means all or nothing. If there is an exception thrown somewhere in the method, changes are not persisted in the database. Something called rollback
happens.
If you don't specify @Transactional
, each DB call will be in a different transaction.
The class declares @Transactional
on itself or its members, Spring creates a proxy that implements the same interface(s) as the class you’re annotating. In other words, Spring wraps the bean in the proxy and the bean itself has no knowledge of it.
A proxy provides a way for Spring to inject behaviors before, after, or around method calls into the object being proxied.
Internally, its the same as using a transaction advice (using AOP), where a proxy is created first and is invoked before/after the target bean’s method.
The generated proxy object is supplied with a TransactionInterceptor
, which is created by Spring. So when the @Transactional
method is called from client code, the TransactionInterceptor
gets invoked first from the proxy object, which begins the transaction and eventually invokes the method on the target bean. When the invocation finishes, the TransactionInterceptor
commits/rolls back the transaction accordingly
To get familiar with @Transactional
annotation in general, please take a look at this article. To dig deeper please refer spring docs.
Generally the @Transactional
annotation is written at the service level.
It is used to combine more than one writes on a database as a single atomic operation.
When somebody call the method annotated with @Transactional
all or none of the writes on the database is executed.
In the case of read operations it is not useful and so it is in case of a single atomic write. You are using it in a single read (select) so adding or removing the @Transactional
annotation has no impact.