Logo InterviewVault

Welcome back, Sujit Kumar Mishra

SKM

Revision Mode

Document technical questions and best-practice answers.

Cancel

What is composite key in JPA?

A composite key in JPA is a primary key made up of more than one column (field). Instead of using a single field to uniquely identify each row in a table, a combination of two or more fields is used together as the unique identifier. In JPA, you can create a composite key by using either @Embeddable and @EmbeddedId or by using @IdClass. This is useful when no single field is unique by itself, but the combination is unique.


Example:

Suppose you have an OrderItem entity where each order can have multiple items, and each item can appear in multiple orders. The combination of orderId and itemId uniquely identifies each record.

1: Create the Composite Key Class

import java.io.Serializable;
import javax.persistence.Embeddable;

@Embeddable
public class OrderItemId implements Serializable {
    private Long orderId;
    private Long itemId;

    // Constructors
    public OrderItemId() {}
    public OrderItemId(Long orderId, Long itemId) {
        this.orderId = orderId;
        this.itemId = itemId;
    }

    // Getters and Setters
    public Long getOrderId() { return orderId; }
    public void setOrderId(Long orderId) { this.orderId = orderId; }

    public Long getItemId() { return itemId; }
    public void setItemId(Long itemId) { this.itemId = itemId; }

    // equals() and hashCode() methods
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        OrderItemId that = (OrderItemId) o;
        return orderId.equals(that.orderId) 
                              && itemId.equals(that.itemId);
    }

    @Override
    public int hashCode() {
        return java.util.Objects.hash(orderId, itemId);
    }
}

2: Create the Entity Class Using Composite Key

import javax.persistence.*;

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

    private int quantity;

    // Constructors
    public OrderItem() {}
    public OrderItem(OrderItemId id, int quantity) {
        this.id = id;
        this.quantity = quantity;
    }

    // Getters and Setters
    public OrderItemId getId() { return id; }
    public void setId(OrderItemId id) { this.id = id; }

    public int getQuantity() { return quantity; }
    public void setQuantity(int quantity) { this.quantity = quantity; }
}

How it works

- The OrderItemId class is used as a composite key (primary key made of orderId and itemId).

- The OrderItem entity uses @EmbeddedId to include the composite key.

- Each OrderItem is uniquely identified by the combination of orderId and itemId.

Summary

Here, OrderItemId (with orderId and itemId) acts as the composite key for the OrderItem entity. This means each row is uniquely identified by the combination of orderId and itemId.

Ready for commit