Search code examples
springspring-bootspring-aopspring-transactions

Does it make sense to use Spring's @Transactional annotation in a method which doesn't talk to database?


I am trying to understand a project which involves spring's declarative transactional annotation. The body of the function is not making any JDBC calls or calling JPA repository methods. All it is doing is call some third party API and transform it's results, it's not even saving the response in the database. So no database interactions at all.

My question is that is it worth using @Transactional annotation on this method? Because as per my understanding @Transactional only helps in maintaining consistency in databases.


Solution

  • The @Transactional annotation defines the scope of a single database transaction - all it does is it begins the transaction and either commit it or rollback. It allows to manage transaction declarative way rather than do it programatically every time.

    It looks something like this:

    UserTransaction utx = entityManager.getTransaction(); 
    
    try { 
        utx.begin(); 
        // your method invocation here
        utx.commit(); 
    } catch(RuntimeException ex) { 
        utx.rollback(); 
        throw ex; 
    }
    

    By making method @Transactional when there is no database calls you only make its performance worse as redundant steps have to take place when not necessary.