Scrivio Interview library
LeadershipPrincipal6 min read · updated 12 November 2026

An ORM generates most SQL in your company, and many performance problems trace to generated queries. Do you push teams towards hand-written SQL, a SQL-first library like jOOQ, or better ORM use? Explain the long-term choice.

I would not push the whole company in one direction. Most ORM performance problems are usage problems, such as N+1 loads and over-fetching, so the long-term choice is a mixed policy: the ORM for writes and simple aggregate loading, a typed SQL tool such as jOOQ or plain SQL for complex reads and reports, and projections for lists. What makes that policy hold is visibility of the generated SQL in tests and production, plus a realistic view of skills, licensing and maintenance.

Why this question is asked

When most SQL in a company is generated, the database often becomes the place where code problems surface, and a leader soon hears two camps: one says the ORM is the problem and should go, the other says people just use it badly. Interviewers ask this to see whether we can make a durable technical decision from evidence instead of taste, and whether we think about people, tooling and cost as well as queries. In this answer, we will look at where ORM problems really come from, what SQL-first tools give and cost, the mixed policy I would choose, how to make SQL visible so it stays healthy, and how to roll it out.

1Where ORM Problems Really Come From

An ORM, an object-relational mapper such as Hibernate behind Spring Data JPA, turns rows into objects and object changes into SQL. It is very productive for the common case: load an order with its lines, change a field, save it. The trouble starts when developers forget that every object access may be a query. The classic case is the N+1 problem: one query loads a list, then one more query runs for each element when a lazy association is touched.

Java
List<Order> orders = orderRepository.findByStatus(Status.OPEN); // 1 query, 200 orders
for (Order o : orders) {
total += o.getCustomer().getCreditLimit(); // 200 more queries
}
// Fixed in the repository, still with the ORM:
@Query("select o from Order o join fetch o.customer where o.status = :s")
List<Order> findOpenWithCustomer(Status s); // 1 query

Notice that the fix did not leave the ORM. The same is true for over-fetching, loading full entities with 40 columns to show a list of three fields, which a projection solves. When we analyse incidents, a typical pattern is that most trace to N+1 loads, over-fetching or a missing index, and only a minority to queries the ORM truly cannot express well, such as reports with window functions, upserts and bulk updates. That split matters, because replacing the ORM would not fix the majority, which are habits.

2What SQL-First Gives and What It Costs

Hand-written SQL, through JdbcClient or a mapper, and SQL-first libraries such as jOOQ, give us full control. jOOQ generates Java classes from the schema, so a query is written in a SQL-shaped Java API, checked by the compiler and broken at build time when a column is renamed. For a monthly revenue report with window functions or a recursive hierarchy, that control is worth a lot.

The cost is that someone must write and own that SQL. It needs real SQL skills, it needs its own tests against a real database, for example with Testcontainers, and it moves mapping code into the team's hands. jOOQ has an open-source edition for open-source databases such as PostgreSQL and MySQL, while some commercial databases need a paid edition, so licence terms must be checked for our database mix. Hand-written SQL in strings has no compile-time check at all, which is why it must be covered by tests.

3The Mixed Policy I Would Choose

The durable answer is to use each tool where it is strongest, and to write that down so teams do not re-argue it in every design review.

Which tool for which workload
WorkloadDefault toolReason
Create, update, delete of aggregatesJPA / Hibernatedirty checking, cascades, optimistic locking
Load one aggregate by idJPA with fetch planentity graph or join fetch, no N+1
Lists and search screensDTO projectionsonly the columns shown, no entities
Reports, analytics, complex joinsjOOQ or plain SQLwindow functions, CTEs, full control
Bulk loads and mass updatesJDBC batch or COPYbypasses persistence context
Written down once, this table settles most per-query debates.

Notice that this keeps the ORM's productivity for most of the code, where it shines, and removes it from the places where it causes the most incidents. The policy also gives a clear escalation path: when a read becomes complex, the team moves it to typed SQL without debating the whole stack.

4Making Generated SQL Visible

A policy only works if problems are caught before production. The ORM's danger is opaque SQL, so the platform's job is to make it visible. In tests, we can count statements and fail the build when a code path issues more than expected.

Java
// Test with datasource-proxy wrapping the DataSource
QueryCountHolder.clear();
service.loadDashboard(customerId);
assertThat(QueryCountHolder.getGrandTotal().getSelect()).isLessThanOrEqualTo(3); // fails at 201
-- In production, the heaviest statements by total time
SELECT calls, round(total_exec_time) AS ms, left(query, 80)
FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 20;

The first part turns an N+1 regression into a failing test the day it is written. The second gives each team a weekly view of its most expensive statements, which pg_stat_statements groups by normalized query text. Adding SQL logging with bind parameters in the test profile, and Hibernate statistics in staging, completes the picture: the SQL is no longer invisible, so it is no longer a surprise.

5Rolling It Out and Keeping It Healthy

A senior decision also has to survive hiring and time. If we standardised on hand-written SQL, every new engineer would need strong SQL from day one, and thousands of mapping lines would need maintenance. If we kept the ORM with no guard rails, the same incidents would continue. The mixed policy asks for moderate skills from everyone and deep skills from a few, so I would pair it with training on fetch plans and projections, a small group of SQL experts who review complex queries, and templates for jOOQ modules.

I would start with the services behind the most incidents, apply the policy there, and measure the effect: incidents per quarter traced to SQL, the share of database time in pg_stat_statements from known bad patterns, and review time for complex queries. If after two or three quarters the numbers move, the policy spreads with evidence behind it; if not, we learn which part was wrong. That is far cheaper than a migration away from the ORM, which would take years and mostly move the same mistakes into new code.

6Follow-up questions

Would you ever ban the ORM outright?

Only for a narrow context where it does not fit, such as a reporting service that never writes or a high-volume ingestion path. Banning it company-wide throws away its real strengths for CRUD and aggregates and replaces one set of mistakes with a much larger amount of hand-written mapping code.

How do you stop teams from drifting back to bad habits?

Make the cheap check automatic: statement-count assertions in tests for key flows, a dashboard of top statements per service, and SQL review as part of design reviews for new reads. People drift when nothing tells them; they mostly stop when the build does.

What about Spring Data JDBC or MyBatis?

They are reasonable middle grounds. Spring Data JDBC keeps repository convenience without lazy loading or a persistence context, which removes N+1 surprises, and MyBatis keeps SQL in files with mapping support. The policy matters more than the specific library, as long as each choice is written down with its reason.

7Conclusion

In this answer, we saw that most ORM performance problems come from usage, N+1 loads, over-fetching and opaque SQL, and can be fixed without leaving the ORM. SQL-first tools such as jOOQ give control for complex reads at the cost of skills, tests and possibly licences. The long-term choice is a mixed policy with the ORM for writes and simple reads, typed SQL for complex reads and projections for lists, kept healthy by making SQL visible in tests and production and by measuring whether incidents fall.

What to say in the interviewAbout 90 seconds aloud

Open with

I would not swing the whole company to hand-written SQL, and I would not leave things as they are. When I look at incidents traced to generated SQL, most are usage problems: N+1 loads from lazy associations, entities fetched when a projection would do, and queries nobody saw.

Then, if they want more

Those are fixable inside the ORM with fetch joins, entity graphs and DTO projections. Where the ORM really is the wrong tool is reporting, complex joins with window functions, upserts and bulk work.

There I want typed SQL, jOOQ or plain SQL with JdbcClient, accepting that it needs SQL skills, its own tests against a real database, and possibly a commercial jOOQ licence for some databases.

So the long-term policy is mixed: ORM for writes and loading aggregates, projections for lists, typed SQL for complex reads, JDBC batch or COPY for bulk loads, written down so teams stop re-arguing it.

To keep it working I make SQL visible: statement-count assertions in tests so an N+1 fails the build, SQL logging in test profiles, and pg_stat_statements dashboards per service.

I would pilot it on the services with the most incidents, train people on fetch plans, keep a few SQL experts for review, and measure incidents and database time over a few quarters before rolling it out widely.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "An ORM generates most SQL in your company, and many performance problems trace to...": https://scrivio-interview-library.netlify.app/databases/query-optimization/9c9c148e6f/