Why do we need to annotate the Service class with @Transactional in Spring Data JPA

Viewed 336

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

  1. @Transactional
  2. @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?

2 Answers

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 method so annotating a class as a Service doesn't mean spring can assume everything is transactional.

This is a has vs is problem.

An object can be Transactional, or have a member object that is Transactional.

If the object has a member object that is Transactional, it is not automatically Transactional itself.

Object A contains Object B which is Transactional, that does not make Object A Transactional.

Related