Card 03/ 07
Spring Data JDBC vs Spring Data JPA
Neither is the safe default: each is safer for the kind of domain it fits.
Spring Data JDBC and Spring Data JPA both map objects to database rows and both give you repositories. They differ in how much they do for you behind the scenes: JPA tracks, watches and lazily loads; JDBC does none of it. The table compares them, and the last paragraph says which kind of application each suits.
| Compared on | Spring Data JDBC | Spring Data JPA |
|---|---|---|
| Persistence context | None | Yes, with dirty checking |
| Lazy loading | None; loads an aggregate in full | Yes, and it can fail outside a transaction |
| SQL behaviour | Predictable, close to what you would write | Generated, sometimes deferred, occasionally surprising |
| Fits | Simple, mostly flat domains; small services; predictable CRUD | Deep relationships, rich domain models, existing Hibernate experience |
The first two rows cause the third. JPA's watching and lazy loading are why its SQL is harder to predict: a write can happen at commit time, and a query can happen when a field is first read. Spring Data JDBC runs a query when you call a repository method, and at no other time. JPA adds a persistence context (JPA's record of the entities it is tracking in the current transaction), dirty checking (saving changed entities without a call to save()) and lazy loading (fetching related rows only when the code first reads them).
The decision rule. A service with a flat domain and a need for predictable SQL is Spring Data JDBC's case: there is nothing complex enough for a persistence context to be worth its cost. A domain with real relationship depth, where letting the framework manage loading and change tracking saves work, is JPA's case.
← → move through sections and cards