First of all I want to say that I really like the Spring Data abstraction and the way how it helps me to unify handling in the persistence layer of Spring application.
Recently I noticed that Spring Data JDBC came out so I decided to use it in a new Spring Boot (2.3.1) application. In my use case I have one DB schema containing two categories of tables:
That was the story and now to my question :). I'm implementing a Spring @Service
bean with transactional method using @Transactional(propagation = Propagation.REQUIRES_NEW)
. This service method is internally using Spring Data JPA and Spring Data JDBC repositories to manipulate data (CRUD). I'm not using any @Transactional
annotations in my JPA/JDBC repositories (all is default). I'm wondering whether DB modifications I'm doing via JPA repositories are sharing the same DB transaction with modifications I'm doing via JDBC repositories. I would need it to be so.
I know that when I want to share one DB transaction among both types of repositories then it is required that both repositories are using the same DB connection. So somehow the Spring Data JDBC repository would need to use the same DB connection as the EntityManager
(Hibernate Session
) used by Spring Data JPA. Can this be achieved in some way or does it work like this out of the box? Could you please help me to understand how this works internally? Thank you very much in advance!
TL;DR: It should work pretty much out of the box.
Spring Data JDBC uses a JdbcTemplate
under the hood. Actually it is a NamedParameterJdbcTemplate
but that isn't that important.
Armed with that information it becomes obvious that this question contains the actual answer:
What transaction manager should I use for JBDC template When using JPA ?
To wrap it up: As long as you only have a single DataSource
and create a JpaTransactionManager
for that JPA and JDBC will share transactions.
And with a single DataSource
Spring Boot should provide that TransactionManager
for you.