Lesson · JDBC
Beyond Raw JDBC: JdbcTemplate, jOOQ, MyBatis, JPA and Spring Data
14 min readBeyond Raw JDBC
Every data layer answers two questions: who writes the SQL, and how much mapping is automatic. JdbcTemplate keeps your SQL and deletes the ceremony; jOOQ generates a type-safe DSL from your schema; MyBatis maps hand-written statements; JPA and Spring Data trade SQL control for object mapping and reach their limits at bulk work and reporting. All five sit on the JDBC you already know.
What raw JDBC leaves on your desk
You can build a service on Connection and PreparedStatement alone, and the first hundred lines are fine. The cost shows up the tenth time you write the same chores: mapping every row by hand, closing every path, opening and committing transactions, and keeping the schema in step with the code.
try (Connection conn = dataSource.getConnection(); PreparedStatement st = conn.prepareStatement( "SELECT id, name, created_at FROM users WHERE region_id = ?")) { st.setLong(1, regionId); try (ResultSet rs = st.executeQuery()) { List<User> users = new ArrayList<>(); while (rs.next()) { // hand mapping, once per query users.add(new User(rs.getLong("id"), rs.getString("name"), rs.getTimestamp("created_at"))); } return users; } }
- Row mapping: every query converts ResultSet columns into fields by hand, and a column rename becomes a search across files.
- Lifecycle: every connection, statement and result set must be closed on every path, including the exception paths.
- Transactions: commit, rollback and the boundary that decides both are explicit code you own.
- Schema evolution: versioned DDL across environments, a concern no query library covers.
- Identity and caching: whether two reads of the same row are the same object, and whether an update is even detected, are questions you answer per query.
Every tool in this lesson is a different answer to the same list. The question is which chores matter in your application, not which tool is modern.
The one question that sorts the field
Sort the field by two axes instead of brands: who writes the SQL, and how much of the mapping is automatic. At one end the database is the centre of the design and you write statements; at the other the object model is the centre and the tool derives SQL from your mappings.
SQL-first tools give you the whole language, its plans and its vendor features, at the cost of writing and versioning statements yourself. Object-first tools give you CRUD and relationships for free, at the cost of control over which SQL runs and when, and that cost is where performance stories start.
| Tool | Who writes the SQL | What is mapped for you |
|---|---|---|
| JdbcTemplate | you, as SQL strings | rows to objects through your RowMapper |
| jOOQ | you, in a typed DSL generated from your schema | rows to generated records or POJOs |
| MyBatis | you, in XML mappers or annotations | explicit resultMap entries |
| JPA / Hibernate | the provider, from mappings and queries | entities, relationships, dirty checking, lazy loading |
| Spring Data JPA | derived from method names or @Query | the same as JPA, plus repository plumbing |
Most production pain comes from choosing the object-first end by accident. A tool that decides when SQL runs is a decision about your performance model, not just about typing less.
SQL-first, three ways: JdbcTemplate, jOOQ and MyBatis
Spring JDBC is the smallest step off raw JDBC: JdbcTemplate owns the borrow, prepare, execute and close cycle, and a RowMapper owns the row. You still write SQL; you stop writing ceremony. NamedParameterJdbcTemplate adds :name parameters for queries with more than a couple of bindings.
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import java.math.BigDecimal; import java.util.Map; public class RevenueReport { private final NamedParameterJdbcTemplate jdbc; public RevenueReport(NamedParameterJdbcTemplate jdbc) { // built on the pooled DataSource this.jdbc = jdbc; } public BigDecimal paidRevenue(String region) { String sql = """ SELECT SUM(o.total) AS revenue FROM orders o JOIN regions r ON r.id = o.region_id WHERE r.name = :region AND o.status = 'PAID' """; BigDecimal revenue = jdbc.queryForObject(sql, Map.of("region", region), BigDecimal.class); return revenue == null ? BigDecimal.ZERO : revenue; // SUM over no rows is NULL } }
- JdbcTemplate: thin convenience, no ORM and no session. You write the statements, the template handles the lifecycle, and BeanPropertyRowMapper covers the boring mappings. A strong middle ground for SQL-shaped teams and reporting.
- jOOQ: SQL as a type-safe DSL generated from your schema. Tables and columns become Java types, so a renamed column breaks the build instead of production; the sweet spot is complex queries that deserve compile-time checking.
- MyBatis: SQL in XML or annotations with explicit result maps, common in enterprise and legacy stacks where DBAs own the statements. Deliberately not an ORM: no identity map, no dirty checking, no generated SQL.
These three keep the SQL you write, which is why the database team can still read it. Choose them when the query is the interesting part of the problem.
JPA and Hibernate: the object-first side
JPA is a specification and Hibernate is its dominant implementation (the API moved from javax.persistence to jakarta.persistence in Jakarta EE 9). You load entities, change their fields and commit: the persistence context detects the changes, flushes UPDATE statements at the transaction boundary, and returns the same instance for the same row inside one session, which is the identity map.
It costs control. A bulk JPQL UPDATE bypasses the persistence context, so in-memory entities are stale until you refresh or clear them; reporting queries with joins and aggregates often end up as native SQL anyway; and every lazy association is a query you did not write and cannot see.
- N+1 selects: one query for the parents, then one per child association touched. Fix with a fetch join, an entity graph, or a projection that selects the columns the screen needs.
- LazyInitializationException: a lazy field touched after the session or transaction closed, so nothing is left that can fetch it. Fetch inside the transaction or map to a DTO there; do not widen the session to hide it.
- Bulk operations: JPQL UPDATE and DELETE never touch loaded entities, and each dirty entity flushes as its own statement unless you batch.
The ORM decides when SQL runs; you still own which SQL is acceptable. Fetch joins, entity graphs and projections are design decisions, not later optimisations.
Spring Data JPA, and the migration nobody's ORM covers
Spring Data JPA puts repository interfaces over JPA: findById, save, findByEmailContainingIgnoreCase, plus paging and projections. For standard CRUD it removes the last boilerplate, and derived query methods read well until the day they do not.
The escape hatch is explicit: when a method name stops expressing the query, drop to @Query with JPQL, a native query for the database's own dialect, or another tool entirely. Nothing forces one persistence technology per application; reporting endpoints commonly sit on JdbcTemplate or jOOQ beside JPA repositories.
Schema migrations are a separate concern from all of it. Flyway or Liquibase versions the DDL, applies it in order in every environment, and keeps the history reviewable; schema generation from entities is convenient in a demo and not a migration strategy for a database with data in it.
Repositories stop where the method name stops making sense. Treat @Query and a native fallback as part of the design, not a defeat.
Choosing: the table you keep
This is the whole lesson compressed. Read the SQL control and watch-outs columns first: they describe what you will debug at 2 a.m., not what the README advertises.
| Tool | Philosophy | SQL control | Mapping | Best fit | Watch-outs |
|---|---|---|---|---|---|
| JdbcTemplate | SQL-first, thin | total: you write it | row mappers you provide | reporting, SQL-shaped services, teams that want the SQL visible | SQL is not checked at compile time; no identity map or caching to lean on |
| jOOQ | SQL-first, typed | total, compile-checked against the schema | generated records and POJOs | complex queries and reporting where compile-time safety pays | code generation keyed to the schema; licensing differs by database |
| MyBatis | SQL-first, mapped | total, in XML or annotations | explicit result maps | enterprise catalogues where DBAs own the SQL | no compile-time checks; XML and Java drift apart silently |
| JPA / Hibernate | object-first ORM | derived SQL, plus JPQL and native | automatic: entities and relationships | CRUD-heavy domains with rich object graphs | N+1, LazyInitializationException, bulk updates bypass the context |
| Spring Data JPA | object-first repositories | derived or @Query | automatic through JPA | standard CRUD with predictable access patterns | method names outgrow themselves; complex queries move out |
Choose the smallest tool that removes the chores you actually have. Layers above JDBC are trades, not upgrades.
Data layer board who writes the SQL
The object-first ORM: the provider derives SQL from your mappings.
watch-outs
N+1 from lazy associations; LazyInitializationException outside the session; bulk updates bypass the context; aggregate reporting gets awkward.
The marker shows the centre of gravity of each tool. Moving right trades SQL control for mapping the tool does for you, and the watch-outs column is what you trade back.
Why JDBC stays your foundation
Every tool in this lesson ends in Connection, Statement and ResultSet. The concepts are not replaced, they are hidden: transaction boundaries, fetch size, batch inserts, prepared statements, and the connection pool behind the DataSource.
That is why framework problems are usually JDBC problems in disguise. The pool timeout is a borrow without a return; the isolation level is a connection property; the slow insert loop is a missing batch; the query someone built by concatenation is the same injection as the previous lesson.
- Pool and isolation settings stay yours: the provider borrows from the pool you configured, with the isolation level the connection carries.
- Fetch size and batching stay yours: ORMs expose them, or hide them behind defaults you should still know, and the JDBC knobs are the ones that matter.
- Errors arrive wrapped: a framework exception carries a JDBC cause, and the cause chain is where the diagnosis lives.
Learn the layer, keep the floor. Frameworks change; the JDBC concepts underneath them are what every framework error eventually describes.
The leak you cannot see is the N+1
Nothing crashes when a lazy association fires one query per row; the page is merely slow, and the log shows a hundred near-identical selects. Open your SQL log for one request a week and read it, or count statements with Hibernate statistics. The ORM abstraction is safe only while you still know what it emits.
Interview angles
When is JdbcTemplate the right choice?+
When the problem is shaped like SQL and the team is comfortable owning statements: reports, bulk operations, small services. You keep full control and lose the lifecycle and row-mapping boilerplate; you do not get an identity map, dirty checking or lazy loading.
What does jOOQ add over SQL in strings?+
A typed DSL generated from your schema, so tables and columns are Java objects and schema drift fails the build instead of production. You keep full SQL control, including window functions and vendor features, and compose queries in the type system.
Why does JPA produce N+1 selects?+
A lazy association loads on first touch, one query per parent entity, because the provider had no reason to fetch it earlier. A fetch join, an entity graph or a projection makes the fetch explicit and collapses the count.
The pattern is invisible on a test dataset of three rows and lethal at a thousand: one query for the parents, one per child, all in a loop that looks like a simple getter call.
Follow-up: How would you find one in production?
What is LazyInitializationException really telling you?+
That an entity left its session with an unfetched association and something touched it after the transaction closed, so no session remains that could fetch it. Fetch the association inside the transaction or map to a DTO there.
Common misconception: Making the association eager does not fix the boundary; it usually creates the N+1 instead, because the fetch now happens for every load.
Do JPA and Hibernate remove the need for migrations?+
No: versioned, reviewed DDL is a separate concern with its own tool (Flyway, Liquibase). Schema generation from entities is convenient for a demo and not a migration strategy for environments that hold data.
Why learn JDBC if you mostly write repositories?+
Because every framework sits on it: pool settings, isolation levels, fetch size, batching and parameter binding are JDBC concepts. Diagnosing a pool timeout or a slow import ends in the same objects the frameworks wrap.