@Id and @GeneratedValue in JPA
Fast recall
Quick revision
Core answer
Whether you can match a generation strategy to a database and know the IDENTITY-vs-batch performance pitfall
Using IDENTITY with PostgreSQL (kills batch inserts) or AUTO without knowing what it picks
Explain SEQUENCE allocationSize pre-fetching and why IDENTITY forces a per-row flush
Interview-ready guide
Interview answer
A PostgreSQL application can use @SequenceGenerator with allocationSize to obtain a block of ids and batch inserts. MySQL commonly uses IDENTITY because sequences were historically unavailable, though database versions/features and providers evolve. With IDENTITY, Hibernate generally executes the INSERT to learn the key, which interferes with ordinary JDBC insert batching for those entities. Saying it always disables every batching optimization is too broad.
@Id and @GeneratedValue in JPA
Direct Answer
@Id marks the entity identifier. @GeneratedValue requests provider-generated values through AUTO, IDENTITY, SEQUENCE, or TABLE according to provider/database support. No strategy is universally 'best' for a named database. IDENTITY often requires an insert before the id is known and can limit Hibernate insert batching, while pooled sequences can support efficient batching; exact behavior depends on provider, driver, and configuration.
Common Mistakes & Pitfalls
- IDENTITY on PostgreSQL — works, but disables batch inserts (per-row flush to read the id); prefer SEQUENCE.
- SEQUENCE without
allocationSize— JPA hits the DB for each id, losing the batch benefit; set it (e.g. 50) to match the sequence increment. - Manually setting the id after
@GeneratedValue— confuses save's new-vs-existing logic and can cause duplicate-key errors. - AUTO in production — unpredictable; choose the strategy explicitly.
Check your understanding
Answer these without looking back at the article.
- What is the difference between GenerationType.IDENTITY and SEQUENCE?
- Why is GenerationType.TABLE slow?
- Can you have a composite primary key in JPA?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.