background image

Compound Primary Keys

<< LineItemKey Class | Entity Mapped to Multiple Database Tables >>
<< LineItemKey Class | Entity Mapped to Multiple Database Tables >>

Compound Primary Keys

public class LineItem {
...
}
The two fields in LineItem are tagged with the @Id annotation to mark those fields as part of the
compound primary key:
@Id
public int getItemId() {
return itemId;
}
...
@Id
@Column(name=
"ORDERID", nullable=false,
insertable=false, updatable=false)
public Integer getOrderId() {
return orderId;
}
For orderId, you also use the @Column annotation to specify the column name in the table, and
that this column should not be inserted or updated, as it is an overlapping foreign key pointing
at the EJB_ORDER_ORDER table's ORDERID column (see
"One-to-Many Relationship Mapped to
Overlapping Primary and Foreign Keys" on page 713
). That is, orderId will be set by the Order
entity.
In LineItem's constructor, the line item number (LineItem.itemId) is set using the
Order.getNextId
method.
public LineItem(Order order, int quantity, VendorPart
vendorPart) {
this.order = order;
this.itemId = order.getNextId();
this.orderId = order.getOrderId();
this.quantity = quantity;
this.vendorPart = vendorPart;
}
Order.getNextId
counts the number of current line items, adds one, and returns that number.
public int getNextId() {
return this.lineItems.size() + 1;
}
Part
doesn't require the @Column annotation on the two fields that comprise Part's compound
primary key. This is because Part's compound primary key is not an overlapping primary
key/foreign key.
The order Application
The Java EE 5 Tutorial · September 2007
716