Search code examples
spring-boottransactionsspring-transactions

Does adding @Transactional annotation to method is a must when making database calls?


I've been on spring projects for quiet a while and i almost never needed to add @Transactional annotation when dealing with databases. But i already have theoretical knowledge on how transaction are managed in spring boot. I am now wondering whether i was doing wrong when not adding a @Transactional with methods dealing with database.


Solution

  • Answers giving here should fill you in as to why @Transactional can be greatly helpful.

    Basically, it makes it so that every database call made under the annotation are put in the same transaction. The helpful part is that if at any point during the transaction an error is thrown, all the previously data modification made will be reverted, preventing incomplete data being inserted into the database.

    So, to answer your question, unless all your call made to modify data in the database are autonomous, you should add @Transactional. It is likely that adding @Transactional will prevent some bad data in the futur.