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.
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
Asked: 2023-05-20 15:08:45 +0000
Seen: 10 times
Last updated: May 20 '23
How can you use linq to choose a specific column from a datatable?
When attempting to write a Spark dataset to a Hive table, why is it unable to locate the column?
How can I include the hours component to a DateTime column using PowerQuery?
Identify commonalities among the strings in a specific column of a DataFrame.