This project demonstrates how to run two independent Spring Data JPA stacks against the same database: one configured for read-write access and another for read-only access. The accompanying REST API lets you trigger the different code paths so you can see how repository methods behave when they are invoked from a transaction that was started on the other datasource.
The app now uses a shared in-memory H2 database for both datasources so you can run the sample without provisioning MySQL. When the application starts it exposes the H2 console at http://localhost:8080/h2-console with the following connection information:
| Property | Value |
|---|---|
| JDBC URL | jdbc:h2:mem:jpa_test;MODE=MySQL;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;DATABASE_TO_UPPER=false |
| User | sa |
| Password | (empty) |
data.sql seeds a sample member (id 1) and a matching note on startup, so the lazy-loading scenarios work immediately.
./gradlew.bat bootRunMemberAccessController exposes two /api/members/{memberId}/lazy/... endpoints that log which datasource served the entity lookup versus the lazy collection access (see the datasourceUsage array in the responses).
-
Call the
findByIdvariant to see howSimpleJpaRepositorybehaves when a lazy collection is accessed from inside the rw transaction:curl http://localhost:8080/api/members/1/lazy/find-by-id
-
Call the JPQL query variant to compare the datasource usage pattern:
curl http://localhost:8080/api/members/1/lazy/query
Each response lists the noteContents resolved through lazy loading as well as the datasource order (e.g. ["rw","ro","ro"]) so you can observe how the ro repository behaves under an rw transaction boundary.