Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To link a column within a composite foreign key to a column in a composite primary key in JPA, you need to use the @JoinColumn annotation.

Here’s an example:

Assuming there are two tables: Order (orderid, customerid, and orderdate) and OrderItem (orderitemid, orderid, productid, and quantity) and the composite primary key for the Order table is (orderid, customerid), and the composite foreign key for the OrderItem table is (orderitemid, orderid, product_id).

// Order Entity @Entity @Table(name = "order_table") public class Order {

@EmbeddedId
private OrderPK orderPK;

@Column(name = "order_date")
private Date orderDate;

// getter and setter

 // OrderPK EmbeddedId class
@Embeddable
public class OrderPK implements Serializable {

    @Column(name = "order_id")
    private Long orderId;

    @Column(name = "customer_id")
    private Long customerId;

    // getter and setter
}

}

// OrderItem Entity @Entity @Table(name = "orderitem_table") @IdClass(OrderItemPK.class) public class OrderItem {

@Id
@Column(name = "order_item_id")
private Long orderItemId;

@Id
@JoinColumn(name = "order_id", referencedColumnName = "order_id")
@ManyToOne
private Order order;

@Id
@Column(name = "product_id")
private Long productId;

@Column(name = "quantity")
private Integer quantity;

// getter and setter

 // OrderItemPK IdClass
public class OrderItemPK implements Serializable {

    private Long orderItemId;
    private Long orderId;
    private Long productId;
}

}

In the OrderItem Entity, we use the @Id, @JoinColumn, and @ManyToOne annotations to link the orderid column in the OrderItem table to the orderid column in the composite primary key of the Order table. The referencedColumnName attribute of the @JoinColumn annotation is set to “order_id” to indicate the name of the column in the referenced entity.