JPA and Hibernate · senior
Bulk imports, projections and Flyway migrations
Bulk work needs JDBC batching and chunks, not entities one by one. Read-only reports need projections or SQL. Migrations must be safe to run and to roll forward.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- JDBC batching is off by default: set
spring.jpa.properties.hibernate.jdbc.batch_size,order_insertsandorder_updates. With IDENTITY ids Hibernate cannot batch inserts. - Ids set in code make
saveAllcallmerge, which SELECTs every row first. - Memory: one transaction with 5 lakh managed entities and snapshots. Work in chunks: flush and
clear()every batch, or one transaction per chunk. - For pure bulk loads skip entities:
JdbcClientorJdbcTemplate.batchUpdate, an upsert (INSERT ... ON CONFLICT ... DO UPDATE), or PostgreSQL COPY. Make reruns safe with idempotent upserts and chunk checkpoints. - Entities are for changing state. For read-only totals use projections (interface or record based) or a native query or
JdbcClient. Projections add nothing to the persistence context. - Derived queries from method names suit two or three conditions. Beyond that use
@Query, Specifications or Querydsl. - JdbcClient on the same DataSource joins the same Spring transaction as JPA, but flush pending JPA changes before reading with SQL.
- Flyway: a failed migration is recorded in
flyway_schema_historyand new pods refuse to start. MySQL commits each DDL statement on its own, so a migration can apply halfway. PostgreSQL runs DDL inside a transaction. Fix forward: repair the partial change by hand, fix the cause, runflyway repair, ship a new version. Use expand and contract: add nullable columns, backfill, switch code, drop old columns later. Boot 4: Flyway needsspring-boot-starter-flyway. In productionddl-autoisvalidateornone, neverupdate.
The red pen
Common traps: mistake → fix
Mistake: saveAll is fast for 5 lakh rows
Fix: without batching it is one statement per row.
Mistake: Entities are the best way to build a report
Fix: projections or SQL are lighter.
Mistake: ddl-auto=update is fine in production
Fix: use migrations and validate.
Easy to hard
Questions interviewers ask, easy to hard
- A CSV import with saveAll takes 40 minutes. What do you check and change?
- Entity, projection or JdbcClient for a dashboard query?
- A Flyway migration failed halfway on MySQL. What do you do?
- How do you add a NOT NULL column safely?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.