0
0
Spring Bootframework~8 mins

@Id and @GeneratedValue for primary keys in Spring Boot - Performance & Optimization

Choose your learning style9 modes available
Performance: @Id and @GeneratedValue for primary keys
MEDIUM IMPACT
This affects database interaction speed and server response time during entity creation.
Defining primary keys for database entities
Spring Boot
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
Database auto-generates unique IDs, reducing server-side checks and speeding inserts.
📈 Performance Gainreduces insert latency by avoiding manual ID management
Defining primary keys for database entities
Spring Boot
@Id
private Long id; // manually assigned IDs in code
Manually assigning IDs can cause conflicts and requires extra database checks, slowing inserts.
📉 Performance Costadds latency due to extra DB queries for uniqueness checks
Performance Comparison
PatternDB QueriesLockingInsert LatencyVerdict
Manual ID assignmentExtra uniqueness checksNoneHigh due to checks[X] Bad
@GeneratedValue TABLEAdditional query per insertPossible lock contentionMedium[!] OK
@GeneratedValue IDENTITYSingle insert queryNo extra lockingLow[OK] Good
Rendering Pipeline
When saving an entity, the ORM uses @Id and @GeneratedValue to assign a primary key before insert. The chosen strategy affects how many database queries and locks occur.
Database Insert
Transaction Management
⚠️ BottleneckExtra queries or locks for ID generation increase insert latency.
Optimization Tips
1Prefer GenerationType.IDENTITY for minimal insert overhead.
2Avoid manual ID assignment to prevent extra uniqueness checks.
3Avoid GenerationType.TABLE due to extra queries and locking.
Performance Quiz - 3 Questions
Test your performance knowledge
Which @GeneratedValue strategy typically causes the least database overhead during inserts?
AGenerationType.TABLE
BGenerationType.IDENTITY
CManual ID assignment
DGenerationType.SEQUENCE with no caching
DevTools: Database Profiler or SQL Log
How to check: Enable SQL logging in Spring Boot, perform inserts, and observe queries generated for ID assignment.
What to look for: Look for extra SELECT or UPDATE queries related to ID generation and locking delays.