Video in progress

Where do you draw the line between Hibernate/JPA and hand-written SQL (jOOQ, JdbcTemplate) on a team?

For writes and working with aggregates, JPA: dirty checking, optimistic locking and cascades are useful there. For complex reads, reports, bulk operations and PostgreSQL-specific features, SQL (jOOQ or JdbcTemplate). What matters is that the rule is written down and checked in review.

📖 Answer

The extreme version of either side works badly. With "everything JPA", window functions, ON CONFLICT, LATERAL and CTEs don't exist in JPQL, so the team does them by looping over entities in memory, and you get N+1 and OOM. With "everything SQL", there's a lot of manual work for plain CRUD, and things like optimistic locking and auditing get rewritten.

The rules I propose:

Situation Tool
Load, change and save an aggregate JPA
List/search screens JPA DTO projection or jOOQ
Reports, analytics jOOQ / SQL
Bulk update/delete, upsert SQL
Database-specific features (jsonb, FTS, range) SQL

Subtle points:

  • A single transaction. JPA and JdbcTemplate use the same DataSource and the same Spring transaction, but Hibernate may not have flushed its changes yet. You may need entityManager.flush() before the SQL; and rows changed with SQL stay stale in the entities in the persistence context.
  • Cache. If you use the second-level cache, direct SQL bypasses it.
  • Tests. Hand-written SQL is tested on a real PostgreSQL in Testcontainers, not on H2.

For a new service I write an ADR for the team: which tools, in which situation, and how exceptions are agreed. Otherwise every developer writes by habit and you end up with three styles inside one service.