Mapping Composite Keys with JPA and Hibernate
When mapping entities to database tables, it's common to use primary keys to uniquely identify records. Composite keys, consisting of multiple columns, are often used in legacy database systems. Both JPA and Hibernate provide annotations to handle composite keys effectively.
Using EmbeddedId
The EmbeddedId annotation denotes that a Java class represents a composite primary key. It maps the class to the table's clustered primary key. The class must:
Example with EmbeddedId
@Entity public class Time { @EmbeddedId private TimePK timePK; private String src; private String dst; private Integer distance; private Integer price; } @Embeddable public class TimePK { private Integer levelStation; private Integer confPathID; // Constructor, equals(), and hashCode() methods omitted for brevity }
Using IdClass
The IdClass annotation specifies that multiple fields or properties of an entity class make up a composite primary key. The class must:
Example with IdClass
@Entity @IdClass(TimePK.class) public class Time { @Id private Integer levelStation; @Id private Integer confPathID; private String src; private String dst; private Integer distance; private Integer price; } public class TimePK implements Serializable { private Integer levelStation; private Integer confPathID; // Constructor, equals(), and hashCode() methods omitted for brevity }
Choosing Between EmbeddedId and IdClass
EmbeddedId creates a separate class for the composite key, while IdClass uses the entity class itself to hold the primary key fields. EmbeddedId is more explicit and suggests a meaningful entity, while IdClass is better for combinations of fields that don't carry an independent meaning.
References
JPA 1.0 specification: https://jcp.org/en/jsr/detail?id=220
The above is the detailed content of How to Effectively Map Composite Keys in JPA and Hibernate using `@EmbeddedId` and `@IdClass`?. For more information, please follow other related articles on the PHP Chinese website!