Transaction management in Spring Boot and Spring data jpa

Viewed 12929

Altough transaction management works Spring Data Repositories create their own transaction and suspend the active one.

I have following Spring application:

Application class:

@SpringBootApplication
@EnableTransactionManagement
public class SpringbootTxApplication {... }

Service class:

@Service
public class EntityService {
    ...
    public void addEntityWithoutTransaction(MyEntity myEntity) {
        log.debug("addEntityWithoutTransaction start");
        myEntityRepository.save(myEntity);
        log.debug("addEntityWithoutTransaction end");
    }

    @Transactional
    public void addEntityTransaction(MyEntity myEntity) {
        log.debug("addEntityTransaction start");
        myEntityRepository.save(myEntity);
        log.debug("addEntityTransaction end");
    }
}

While exeucting my EntityServiceTest which executes each method once and having spring transaction log in trace, I get following output:

... TRACE ... o.s.t.i.TransactionInterceptor           : Getting transaction for [de.miwoe.service.EntityService.addEntityTransaction]
... DEBUG ... de.miwoe.service.EntityService           : addEntityTransaction start
... TRACE ... o.s.t.i.TransactionInterceptor           : Getting transaction for [org.springframework.data.jpa.repository.support.SimpleJpaRepository.save]
... TRACE ... o.s.t.i.TransactionInterceptor           : Completing transaction for [org.springframework.data.jpa.repository.support.SimpleJpaRepository.save]
... DEBUG ... de.miwoe.service.EntityService           : addEntityTransaction end
... TRACE ... o.s.t.i.TransactionInterceptor           : Completing transaction for [de.miwoe.service.EntityService.addEntityTransaction]

And

... DEBUG ... de.miwoe.service.EntityService           : addEntityWithoutTransaction start
... TRACE ... o.s.t.i.TransactionInterceptor           : Getting transaction for [org.springframework.data.jpa.repository.support.SimpleJpaRepository.save]
... TRACE ... o.s.t.i.TransactionInterceptor           : Completing transaction for [org.springframework.data.jpa.repository.support.SimpleJpaRepository.save]
... DEBUG ... de.miwoe.service.EntityService           : addEntityWithoutTransaction end

Obviously according to the log, the @Transactional-Annotation is working in addEntityTransaction, but the repository still creates its own transaction.

Why? Official docs (https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#transactions) describe it should not begin a new one if it already exists.

(Sometimes, Convention over Configuration seems more like Irritation over Convention over Configuration....)

Am I missing something?

(Complete code is also available here: https://github.com/miwoe/springboot-tx)

2 Answers
Related