Skip to the page

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.

The notes

What you must know

  • JDBC batching is off by default: set spring.jpa.properties.hibernate.jdbc.batch_size, order_inserts and order_updates. With IDENTITY ids Hibernate cannot batch inserts.
  • Ids set in code make saveAll call merge, 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: JdbcClient or JdbcTemplate.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_history and 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, run flyway repair, ship a new version. Use expand and contract: add nullable columns, backfill, switch code, drop old columns later. Boot 4: Flyway needs spring-boot-starter-flyway. In production ddl-auto is validate or none, never update.

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

  1. A CSV import with saveAll takes 40 minutes. What do you check and change?
  2. Entity, projection or JdbcClient for a dashboard query?
  3. A Flyway migration failed halfway on MySQL. What do you do?
  4. 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 voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview