Video in progress
How do you balance database-specific features (stored procedures, window functions, partial indexes, LISTEN/NOTIFY) against Hibernate's portability?
Portability is often a false goal: switching databases rarely happens, but giving up the database's strengths costs money every day. I use database-specific features, but I gather them in a clear place, the repository layer and migrations, and run the tests on the real database.
📖 Answer
Writing the whole codebase in JPQL only, because of the question "what if we move from Oracle to PostgreSQL tomorrow?", is a decision I have seen many times and that has rarely paid off. In real projects, when the database is replaced the migration work is big anyway, and rewriting a few native queries is the smallest part of it.
But "everything in stored procedures" is the other extreme: the logic lives in two places, versioning, testing and debugging are harder, and deployment has two parts.
My limits:
I use freely:
- partial and expression indexes,
jsonb, arrays: in migrations; - reporting queries with window functions and CTEs: native query or jOOQ;
for update skip locked: for queue tables;insert ... on conflict: for upserts.
With caution:
- stored procedures: only when you need to process a large volume of data without pulling it out of the database;
- triggers: only for audit or denormalization, not for business rules;
LISTEN/NOTIFY: for a small signal, not for reliable message delivery.
Hibernate 6 has improved here: HQL supports window functions, CTEs and insert ... values, and with FunctionContributor you can register a database-specific function in HQL.
The rule: native SQL lives only in the repository, and each one has a Testcontainers test. Then even if the database is replaced, it is clear what has to be rewritten.
Sign up to mark studied questions and save your progress.