Reputation: 3850
I have a Order
entity, and a Product
entity. An order may have a number of pairs, representing the product and the number sold. What is an approprate relation in JPA to represent it?
(So far I have only found methods to associate a collection of EntityA with EntityB. e.g. EntityA contains a List<EntityB>
. )
Upvotes: 0
Views: 373
Reputation: 1
I am also using the above code but it is not working for me. Below is my code.
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name="content_package_component_level_languages_language_assessment_map", joinColumns=@JoinColumn(name="id"))
@MapKeyJoinColumn(name="language_assessment_map_key", referencedColumnName = "id")
@Column(name="language_assessment_map")
private Map<Lang, Integer> languageAssessmentMap;
Upvotes: 0
Reputation: 40296
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;
}
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.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.
Upvotes: 1
Reputation: 880
you have to map entity like
In Order.jave
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "order_Id")
@JsonBackReference
private List<Product> product = new ArrayList<Product>();
In Product.jave
@ManyToOne
@JoinColumn(name = "product_Id", referencedColumnName = "product_Id", nullable = false, insertable = false, updatable = false)
@JsonBackReference
private Order order;
Upvotes: 0