1

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

如果你有这样的关系:

在此处输入图像描述

如前所述,一个产品可以在没有订单的情况下存在(通常它们将在新产品到达时添加)稍后它可以用于一个或多个订单。订单必须包含至少 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 是否为我执行此操作?

4

2 回答 2

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

  2. 您必须手动更新关系的另一方。JPA 不会为您这样做。(当然,如果您保存一个订单,然后重新获取产品,您的订单集合将被更新)

编辑 解释第二点:

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
于 2013-01-04T10:52:01.413 回答
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;
    ...
    ...
}

对?还是我看错了

于 2013-01-07T10:22:39.617 回答