What is a Composite Key in Hibernate?

A composite key in Hibernate is a primary key made up of more than one column, mapped in Java by grouping those columns into a dedicated key class rather than a single field.

Key Points: • @EmbeddedId places a single field of a custom, @Embeddable-annotated class on the entity to represent the whole composite key. • @IdClass is an alternative where the entity itself declares the individual key fields, and a separate class mirrors them for identity comparison. • The key class must implement Serializable and override equals() and hashCode() correctly, since Hibernate uses these for identity checks and caching. • Composite keys are common when mapping legacy schemas or many-to-many join tables that carry no single natural surrogate key. • Using a composite key impacts how you write HQL/JPQL queries — you reference the embedded fields via dot notation.

Example: An OrderItem table keyed by (order_id, product_id) can be modeled with an OrderItemId class holding those two fields, embedded into OrderItem via @EmbeddedId, so orderItem.getId().getProductId() retrieves part of the key.

Code Example:

@Embeddable
public class OrderItemId implements Serializable {
    private Long orderId;
    private Long productId;
    // equals(), hashCode(), getters/setters
}

@Entity
public class OrderItem {
    @EmbeddedId
    private OrderItemId id;
}

Interview Tip: A concise interview answer is:

"A composite key is a primary key spanning multiple columns, and in Hibernate I model it with a separate Serializable class marked @Embeddable and referenced from the entity with @EmbeddedId, or alternatively with @IdClass — either way that key class needs correct equals() and hashCode() implementations."