JPA有很多关系:零或更多

时间:2013-01-04 10:42:22

标签: java jpa

我是JPA的新手所以我有一个关于多对多关系的问题(实现零到多):

如果你有这样的关系:

enter image description here

如上所述,产品可以在没有订单的情况下进行排序(通常在新产品到货时会添加),以后可以在1个或更多订单上使用。订单必须包含至少1个或更多产品。

你必须陈述关系

@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<Product> productList;       
 ...............
   The other attributes and getters and setters goes here
}

@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<Order> orderList;       
   ...............
   The other attributes and getters and setters goes here
}

我想知道零到多关系是否仍然可以只保留那些没有链接(目前)订单的产品?

但是当订单使用产品时,产品中的订单列表应该更新,而产品列表也应该更新。我如何强制执行此操作或为我做JPA?

2 个答案:

答案 0 :(得分:0)

  1. 您仍然可以在没有订单的情况下保留产品。

  2. 您必须手动更新关系的另一面。 JPA不会为你做那件事。 (当然,如果您保存一个订单然后重新获取产品,您的订单将会更新)

  3. 修改 解释第二点:

    Product persitentProduct = ... //some product
    Order newOrder = new Order();
    newOrder.getProducts().add(persitentProduct);
    //at this point : persistentProduct.getOrders().contains(newOrder)==false
    entityManager.persist(newOrder);
    //at this point nothing has changed on the other side of the relationship:
    // i.e. : persistentProduct.getOrders().contains(newOrder)==false
    

答案 1 :(得分:0)

然后你会得到类似的东西:

public class Order {
private List products;
...
public void addProduct(Product product) {
    this.products.add(product);
    if !(product.getOrders().contains(product) {
        product.getOrders().add(this);
    }
}
...
}



public class Product {
    private List orders;
    ...
    ...
}

正确?或者我看错了