If the quantity is all there is to this association and you do not need to navigate from Product
→Order
, you can consider the Integer quantity
as an element collection and do the following - Product
stays the same:
public class Order {
@ElementCollection // 1
@CollectionTable(name="ORDER_PRODUCT_QTY") // 2
@MapKeyJoinColumn(name="PRODUCT_ID") // 3
@Column(name="QUANTITY") // 4
private Map<Product, Integer> quantities;
}
- It is a collection of basic types (integers for the quantity), keyed by the entity
- It is multivalued, so needs a separate table; you optionally want to specify its name
- The separate collection table will contain column(s) pointing to the
Order
entity, column(s) pointing to the Product
and a column for the quantity value itself. This lets you set the name of the FK referencing the Product
table and is optional.
- This lets you specify the name of the column holding the quantity value. Optional too.
If you have reasons to believe that this is not enough then you may want to create a distinct entity representing the association, like:
Order
← OrderItem
→ Product
Order
has many OrderItem
s, Product
has many OrderItem
s, Order
has many Product
s indirectly through OrderItem
, Product
can be found in many Order
s, indirectly through OrderItem
and the quantity is in the OrderItem
. Representing this kind of "relation with value" as an entity is more flexible than collection mapping.