Consider this class:
@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
And this one:
@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
}
Now, if I want to add a product to an order I just do this:
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();
The above example works - I can see it in the database. If I instead do this:
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();
The database isn't updating in the above example. Shouldn't it work both ways? Is there something I should do?
Hank
Try add cascade on your @ManyToMany option like this :
See the Hibernate Documentation which is very clear on this issue