Mapping Composite Keys with JPA and Hibernate
Mapping composite keys in Java Persistence API (JPA) and Hibernate can be achieved using the EmbeddedId or IdClass annotations.
With IdClass
- Define a separate primary key class (e.g., TimePK) that encapsulates the composite key fields and their getters/setters.
- Annotate the entity with the @IdClass annotation, specifying the primary key class.
With EmbeddedId
- Similarly, define a separate primary key class (e.g., TimePK).
- Annotate the primary key class with the @Embeddable annotation.
- Annotate the entity with the @EmbeddedId annotation and specify the primary key class.
Differences
-
Semantic: EmbeddedId suggests that the composite key has a specific meaning, while IdClass is more suitable when the combination of fields is simply a unique identifier.
-
Query Syntax: With EmbeddedId, the primary key fields are accessed through the embedded primary key class, while with IdClass the fields can be accessed directly.
References
- JPA 1.0 Specification: Section 2.1.4, 9.1.14, and 9.1.15
The above is the detailed content of How to Map Composite Keys in JPA and Hibernate using EmbeddedId or IdClass?. For more information, please follow other related articles on the PHP Chinese website!