Junior — Middle
How is a composite primary key created in Hibernate?
sobes.tech AI
Answer from AI
In Hibernate, a composite primary key is created using the @Embeddable annotation for the class describing the key, and @EmbeddedId in the entity.
Example:
@Embeddable
public class OrderId implements Serializable {
private Long orderId;
private Long productId;
// constructors, getters, setters, equals, and hashCode
}
@Entity
public class Order {
@EmbeddedId
private OrderId id;
private int quantity;
// other fields, getters, setters
}
Thus, the class with the composite key must be serializable and override equals and hashCode. The entity uses a field annotated with @EmbeddedId.