In the provided code, a composite key is defined for the Time table with levelStation and confPathID as its components. To map this composite key in JPA and Hibernate, you have two options: @EmbeddedId and @IdClass.
The @IdClass annotation allows you to map multiple fields of the entity to form the composite primary key. This requires defining a class that represents the primary key. In this case, the TimePK class can be defined as follows:
@IdClass(TimePK.class) public class Time implements Serializable { // ... }
Here, TimePK is a separate class that must define a no-arg constructor, getters/setters for the primary key fields, and equals() and hashCode() methods.
The @EmbeddedId annotation maps an embedded class to the primary key of the entity. As opposed to @IdClass, this approach combines the entity class and the primary key class. Here's how you would use @EmbeddedId:
@Entity class Time implements Serializable { @EmbeddedId private TimePK timePK; // ... }
In this case, TimePK is an inner class of the Time entity and must also define a no-arg constructor, getters/setters for the key fields, and equals() and hashCode() methods.
The main difference between @IdClass and @EmbeddedId is their impact on query syntax. With @IdClass, you would access the primary key field directly via the entity, while with @EmbeddedId, you would access it through a getter on the embedded class.
When choosing between the two, @EmbeddedId conveys the fact that the primary key has a meaningful identity in your domain model, while @IdClass suggests that the primary key is simply a combination of fields that uniquely identifies the entity.
JPA 1.0 Specification:
The above is the detailed content of How to Map Composite Keys in JPA and Hibernate using @EmbeddedId vs. @IdClass?. For more information, please follow other related articles on the PHP Chinese website!