java - Hibernate foreign key is null in OrderItem (order_orderID) -
i have 2 table orders
, orderitem
below:
@entity @table(name = "orders") public class order implements serializable { @id @generatedvalue private integer orderid; @column(nullable = false) private date orderdate; @manytoone(cascade = cascadetype.all) private user user; @onetomany(cascade = cascadetype.all) private set<orderitem> orderitems = new hashset<orderitem>(); public order() { } public order(date ordate, user currentuser) { this.orderdate = ordate; this.user = currentuser; } public set<orderitem> getorderitems() { return orderitems; } public void setorderitems(set<orderitem> orderitems) { this.orderitems = orderitems; } //getter/setters orderdate, user
and
@entity public class orderitem implements serializable { @id @generatedvalue private integer id; @manytoone(cascade = cascadetype.all) private book book; // f.k book table @column(nullable = false) private int quantity; @column(nullable = false) private double totalprice; public orderitem() {} public orderitem( book currentbook, int qty, double totalprice) { this.book = currentbook; this.quantity = qty; this.totalprice = totalprice; } //getter/setters
and here initialize them store in database:
@transactional public void storeorderindb() { order = new order(currentdate(), currentuser); //date,user orderservice.addorder(order); orderitem orderitem = new orderitem(); orderitem.setbook(currentbook); orderitem.setquantity(qty); orderitem.settotalprice(gettotalcost(qty, unitprice)); orderitemservice.addorderitem(orderitem); }
this result:
orders
:
orderid: 5, orderdate: "2015-04-25 23:11:16", userid: 1
orderitem
:
id:2 , quantity:1 , totalprice:5000 , bookid:5 , order_orderid: null
why order-orderid
null
?
i need not null.
in order entity
have declared
@onetomany(cascade = cascadetype.all) private set<orderitem> orderitems = new hashset<orderitem>();
above declaration says foreign-key maintain order entity , resolve problem
@transactional public void storeorderindb() { order order = new order(currentdate(), currentuser); //date,user orderitem orderitem = new orderitem(); orderitem.setbook(currentbook); orderitem.setquantity(qty); orderitem.settotalprice(gettotalcost(qty, unitprice)); //orderitemservice.addorderitem(orderitem); set<orderitem> orderitemset=order.getorderitems(); orderitemset.add(orderitem); order.setorderitems(orderitemset); orderservice.addorder(order); }
hope resolve problem thanks!
Comments
Post a Comment