Composite keys in JPA and Hibernate

Use embeddable objects to join two primary keys into one composite key

Conceptual image of a digital circuit-board key amid binary code.
liulolo / Getty Images

Every JPA entity has a primary key, but some entities have more than one value as their primary key. In this case, you need to use a composite key. This Java tip introduces you to using composite keys in JPA and Hibernate.

When you need a composite key

Consider a product pricing table that stores product prices based on both a region name and a product ID. In this case, your table could include multiple rows with the same product ID, but each associated with a different region. You'll need both the product ID and the region name to uniquely differentiate between product prices in different regions.

We'll use two JPA constructs to solve this problem:

To continue reading this article register now