Ask Your Question
1

In JPA, what is the procedure for linking a column within a composite foreign key to a column in a composite primary key?

asked 2023-05-20 15:08:45 +0000

huitzilopochtli gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted
1

answered 2023-05-20 15:11:02 +0000

djk gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-20 15:08:45 +0000

Seen: 10 times

Last updated: May 20 '23