Mapping Composite Keys with JPA and Hibernate
In the provided SQL schema, the Time table has a composite primary key consisting of levelStation and confPathID fields. Mapping this type of key in JPA and Hibernate requires special annotations to represent the compound primary key.
Using the IdClass Annotation
One option is to define a Java class for the composite key using the @IdClass annotation. The class should have fields corresponding to the primary key columns, as well as getters, setters, equals, and hashCode methods:
1 2 3 4 5 6 |
|
The entity class is then annotated with @IdClass and the composite key object:
1 2 3 4 5 6 7 8 9 10 |
|
Using the EmbeddedId Annotation
Alternatively, you can use the @EmbeddedId annotation to define a class containing the composite key:
1 2 3 4 5 6 7 |
|
The entity class is then annotated with @EmbeddedId and the embedded composite key object:
1 2 3 4 5 6 7 |
|
Differences between IdClass and EmbeddedId
Both @IdClass and @EmbeddedId allow mapping of composite primary keys. However, there are some minor differences:
The choice between @IdClass and @EmbeddedId depends on the specific semantics of your application.
The above is the detailed content of How to Map Composite Keys with JPA and Hibernate Using `@IdClass` or `@EmbeddedId`?. For more information, please follow other related articles on the PHP Chinese website!