以两种方式将数据添加到多对多关系中的对象,

时间:2014-11-13 11:47:22

标签: java jpa many-to-many openjpa

考虑这个课程:

@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;

   @OneToOne(optional=false,cascade=CascadeType.ALL, mappedBy="order",
   targetEntity=Invoice.class)
   private Invoice invoice;

   @ManyToOne(optional=false)
   @JoinColumn(name="CUST_ID",referencedColumnName="CUST_ID")
   private Customer customer;

   @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

}

现在,如果我想在订单中添加产品,我就这样做:

    EntityManagerFactory emFactory = Persistence.createEntityManagerFactory("something");
    EntityManager em = emFactory.createEntityManager();
    EntityTransaction trans = em.getTransaction();

    trans.begin();

    Order order = em.find(Order.class, 1);
    Product product = em.find(Product.class, 51);

    order.getProductList().add(product);

    trans.commit
    em.close();
    emFactory.close();

以上示例有效 - 我可以在数据库中看到它。如果我这样做:

 EntityManagerFactory emFactory = Persistence.createEntityManagerFactory("something");
    EntityManager em = emFactory.createEntityManager();
    EntityTransaction trans = em.getTransaction();

    trans.begin();

    Order order = em.find(Order.class, 1);
    Product product = em.find(Product.class, 51);

    product.getOrderList().add(order);

    trans.commit
    em.close();
    emFactory.close();

在上面的示例中,数据库没有更新。它不应该双向工作吗?有什么我应该做的吗?

汉克

2 个答案:

答案 0 :(得分:0)

首先,你应该始终设置关系的两面。

当您仅从产品方面进行设置时,它不起作用的原因是该关系归订单方所有。

答案 1 :(得分:-1)

尝试在@ManyToMany选项上添加级联,如下所示:

@ManyToMany(
        mappedBy="productList",
        fetch=FetchType.EAGER,
        cascade = {CascadeType.ALL}
)

请参阅此问题非常明确的Hibernate Documentation