Issue
In a spring boot app, we have user-defined repository interface that extends JpaRepository. JpaRepository in turn is has an implementation class SimpleJpaRepository. SimpleJPARepository has 2 annotations on it
- @Transactional
- @Repository
So we can skip these 2 annotations on our user-defined repository interface that extends JpaRepository. Then why do we need to explicitly add @Transactional over service class which is also using our user-defined repository object only?
Solution
The point of having the Transactional annotation is so that everything in the annotated method occurs within the same unit of work and either everything succeeds or everything fails. Putting Transactional only on each repository means each repository can have its own transaction, and the second one failing doesn't rollback the first one.
You can have nontransactional methods on a service, or every metho so annotating a class as a Service doesn't mean spring can assume everything is transactional.
Answered By - Nathan Hughes
Answer Checked By - Mary Flores (JavaFixing Volunteer)