What is the use of @Transactional with JPA and Hibernate?

后端 未结 4 546
半阙折子戏
半阙折子戏 2021-02-09 04:24

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

4条回答
  •  北海茫月
    2021-02-09 04:45

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

    1. We decrease A's account by 100$
    2. We add 100$ to B's account

    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.

提交回复
热议问题