title: JPA many to many relationship : zero or more
body: <p>I'm new to JPA so I have a question about a many to many relationship (with a zero to more implementation) :</p>
  
  <p>If you have a relationship like :</p>
  
  <p><img src="https://i.stack.imgur.com/xe4uy.jpg" alt="enter image description here"></p>
  
  <p>Like stated a product can excist without a order (normally they will be added as new products arrive) later on it can be used on 1 or more orders.  An order must contain at least 1 or more products.</p>
  
  <p>you must state the relationship</p>
  
  <pre><code>@Entity(name = "ORDERS") 
  public class Order {
         @Id 
         @Column(name = "ORDER_ID", nullable = false)
         @GeneratedValue(strategy = GenerationType.AUTO)
         private long orderId;
  
     @Column(name = "CUST_ID")
     private long custId;
  
     @Column(name = "TOTAL_PRICE", precision = 2)
     private double totPrice;     
  
     @ManyToMany(fetch=FetchType.EAGER)
     @JoinTable(name="ORDER_DETAIL",
             joinColumns=
             @JoinColumn(name="ORDER_ID", referencedColumnName="ORDER_ID"),
       inverseJoinColumns=
             @JoinColumn(name="PROD_ID", referencedColumnName="PROD_ID")
     )
     private List&lt;Product&gt; productList;       
   ...............
     The other attributes and getters and setters goes here
  }
  </code></pre>
  
  <p>and</p>
  
  <pre><code>@Entity(name = "PRODUCT") 
  public class Product {
         @Id
         @Column(name = "PROD_ID", nullable = false)
         @GeneratedValue(strategy = GenerationType.AUTO)
         private long prodId;
  
     @Column(name = "PROD_NAME", nullable = false,length = 50)
     private String prodName;
  
     @Column(name = "PROD_DESC", length = 200)
     private String prodDescription;
  
     @Column(name = "REGULAR_PRICE", precision = 2)
     private String price;
  
     @Column(name = "LAST_UPDATED_TIME")
     private Date updatedTime;
     @ManyToMany(mappedBy="productList",fetch=FetchType.EAGER)
     private List&lt;Order&gt; orderList;       
     ...............
     The other attributes and getters and setters goes here
  }
  </code></pre>
  
  <p>I wonder the zero to many relation is it still possible to just persist products who aren't linked (at the moment) to a order?  </p>
  
  <p>But when a order uses a product the orderlist in product should be updated and the productlist in orde also.  How do I enforce this or does JPA this for me?</p>