SQL JPA - Multiple columns as primary key
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.
Introduction
Composite primary keys are necessary when uniqueness comes from a combination of columns instead of a single identifier. In JPA, this is modeled using either @IdClass or @EmbeddedId, each with different ergonomics for queries and relationships. Correct mapping is mostly about consistency, especially around equality methods and foreign-key relations.
Core Sections
Decide if composite key is truly required
Before mapping, confirm business identity really needs multiple columns. Composite keys work well for join tables and natural-key domains, but they make entity APIs and relationships more complex than a single surrogate key.
If your table has a stable synthetic id and unique constraint on business columns, that design is often easier for long-term maintenance.
Mapping with @EmbeddedId
@EmbeddedId keeps key fields in a dedicated embeddable type and embeds it in the entity.
This style keeps key logic grouped and usually reads better for complex keys.
Mapping with @IdClass
@IdClass keeps key fields directly in entity and uses external key class for identity contract.
@IdClass can be convenient in legacy schemas because entity fields remain flat, but duplication between entity fields and key class is easier to misconfigure.
Model relationships with @MapsId
For composite keys involving foreign keys, @MapsId makes relations explicit and avoids manual synchronization bugs.
This ties embedded key values to related entity identifiers cleanly.
Querying entities with composite keys
With @EmbeddedId, lookups use key object.
For JPQL, key fields are accessed through key path:
Plan query style early so repository code remains consistent.
Equality and hash code requirements
Incorrect equals and hashCode in key class cause hard-to-debug cache and collection behavior issues. Use immutable semantics where possible and include all key fields.
Do not include non-key mutable fields in identity methods.
Migration and schema evolution considerations
Changing composite key fields later is expensive because all related foreign keys and application mappings must be updated. If you expect key structure to evolve, consider surrogate id plus unique constraint pattern.
For existing schemas, keep DDL and JPA mappings versioned together so environments do not drift.
Testing and validation strategy
Add tests for:
- insert and find by composite key,
- duplicate key constraint enforcement,
- relationship loading with
@MapsId.
Integration tests should run against the same database type used in production whenever possible.
Common Pitfalls
- Forgetting
Serializableon key class and breaking JPA requirements. - Implementing
equalsandhashCodeinconsistently across key fields. - Mixing
@IdClassand embedded-key assumptions in repository queries. - Omitting
@MapsIdand manually desynchronizing key and relation fields. - Choosing composite keys where a surrogate key plus unique constraint is simpler.
Summary
- Use composite keys only when business identity truly requires multiple columns.
- Choose
@EmbeddedIdfor grouped key modeling or@IdClassfor flatter legacy mappings. - Implement key equality methods correctly and include all key parts.
- Use
@MapsIdfor foreign-key-based composite identity relationships. - Cover key mapping behavior with integration tests to prevent persistence regressions.
Related reading
- SQL keys, MUL vs PRI vs UNI
- SQL multiple column ordering
- sql multithreading application select and delete from a table
- SQL MySQL vs NoSQL CouchDB
- SSH library for Java
- SSL handshake alert unrecognized_name error since upgrade to Java 1.7.0
- SQL order string as number
- SQL query return data from multiple tables

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.