I have 3 entities named Stock,StockHistory and StockOpenClose. And there is common column stock_id in each entity. My problem is that, I have to save list of data into each.
for (Stock stok : stockList) {
session.saveOrUpdate(stok);
session.flush();
for (StockOpenAndClose openStk : stockOpenCloseList) {
if (stockOpenCloseList != null) {
openStk.setStock_id(stok.getStock_id());
session.save(openStk);
session.flush();
}
}
for (StockHistory stkHis : stkHisList) {
stkHis.setStock_id(stok.getStock_id());
session.saveOrUpdate(stkHis);
session.flush();
}
}
I am saving like this and data are saving.And I know this is wrong. Because stock_id will be same according to the for each loop iteration. I want get the corresponding stock_id in both StockHistory , StockOpenClose entities. How can I do that??Can anyone correct me?
did you mean like this?
for (int i = 0; i < stockList.size(); i++) {
Stock stok = stockList.get(i);
StockOpenAndClose openStk = stockOpenCloseList.get(i);
StockHistory stkHis = stkHisList.get(i);
session.saveOrUpdate(stok);
session.flush();
openStk.setStock_id(stok.getStock_id());
session.save(openStk);
stkHis.setStock_id(stok.getStock_id());
session.saveOrUpdate(stkHis);
session.flush();
}
but it will be better and simpler if you learn about "hibernate cascade" here some example
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.