Card 03/ 07

ComparisonDifficulty: Advanced1 min

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.

Spring Data JDBC compared with Spring Data JPA
Compared onSpring Data JDBCSpring Data JPA
Persistence contextNoneYes, with dirty checking
Lazy loadingNone; loads an aggregate in fullYes, and it can fail outside a transaction
SQL behaviourPredictable, close to what you would writeGenerated, sometimes deferred, occasionally surprising
FitsSimple, mostly flat domains; small services; predictable CRUDDeep 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.