The Java Persistence Series

Java tip: Composite keys in JPA and Hibernate

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

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:

  • Embeddable Object: We'll create a new class, ProductPriceId, that is annotated with the @Embeddable annotation and holds both the product ID and the region name, which represents the primary key of a product price.
  • Embedded ID: We'll create the ProductPrice entity and reference the ProductPriceId as its id, using the @EmbeddableId annotation.

To continue reading this article register now