Sql JPA - Multiple columns as primary key
Give a heart to @IdClass
- it's all about composite primary key magic in JPA:
Composite Key Class:
Entity class with a composite key:
Equals()
and hashCode()
are your go-to friends in the CompositeKey
class. The @Id
annotations are the shining badges for keyPart1
and keyPart2
, marking them as the composite primary key.
Nailing other composite key options
Besides going the @IdClass
route, JPA is also buddies with @Embeddable
and @EmbeddedId
for setting up composite keys. The best friend to pick depends on the situation. Sure-fire rule - always let your composite key classes jump on the Serializable
bandwagon.
Dancing with column order and performance
The rules of the composite primary key dance are simple: the order of fields does matter. Hibernate is the experienced partener who will guide the moves - table definitions and index/constraint definitions. Choosing the right name and order of dance steps (aka key-fields) can field you the trophy of optimized database operations.
Here come equals() and hashCode()
JPA loves the equals()
and hashCode()
dynamic duo in the composite key class. Why? Once the session cache needs an entity, or handling entity instances in different persistence contexts is necessary, these two save the day.
The art of naming and using strategies
Field names - not just a pretty face
Clear and understandable field names in your key class are your best friends. They make the model easy to read, understand, and extend.
Composite Key Defining Tactics:
To be @IdClass or to be @EmbeddedId
-- @IdClass
: You're dealing with a legacy database or want to work with the key class separately. It's simpler but can play hardball with the object-oriented approach.
-- @EmbeddedId
: You're looking for a more object-oriented solution. It lets you wrap the composite key in another @Embeddable
class.
Serializable - Not, not just a buzzword
Make your key class Serializable
for JPA compatibility. This lets keys pass in a detached state, ensuring that entity instances with composite keys can safely wave goodbye (serialize).
Indices and constraints - A love story
Rummy rules of order
The order of fields in your @IdClass
or @EmbeddedId
can either raise or sink the effectiveness of your database indices. Play your cards right and order your fields to improve efficiency.
Naming constraints - Not just a game
JPA lets you specify constraint names - use it to clear the path for developers and DBAs when they encounter relationship constraints in the database schema.
Was this article helpful?