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.