Search code examples
javaspringspring-bootspring-transactions

Spring @Transactional best practices


i wanna know if my implementation of @Transactional is correct or not.

when I got to know @Transactional for the first time, i used it in my repository classes, above each method that makes multiple calls to mongodb at once. But, i stopped using that approach, and put @Transactional above my service classes, so that each method of my services runs in a single transaction. for example, find an object from the database, validate the user input, then modify the object and save it in the database .. knowing that sometimes I need to throwe a exception, like not found, or bad request...

is my implementation correct?


Solution

  • Yes, usually service methods are annotated with @Transactional when you want everything in that method to happen in one transaction.