modeller
modeller

Reputation: 3850

How to represent a Map<EntityType, Integer> relation using JPA?

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

Answers (3)

KESHAV
KESHAV

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

Nikos Paraskevopoulos
Nikos Paraskevopoulos

Reputation: 40296

If the quantity is all there is to this association and you do not need to navigate from ProductOrder, 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;
}
  1. It is a collection of basic types (integers for the quantity), keyed by the entity
  2. It is multivalued, so needs a separate table; you optionally want to specify its name
  3. 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.
  4. 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:

OrderOrderItemProduct

Order has many OrderItems, Product has many OrderItems, Order has many Products indirectly through OrderItem, Product can be found in many Orders, 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

SF..MJ
SF..MJ

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

Related Questions