Please no offence if this is a repeat query.
How can a new child record be inserted into a child table
for which a parent is already existing?
(i.e How can I add record no 2 with status of 'Executed'
to child table only?)
My code below does not add a new Child.
Code:
Trade (Parent) TradeDetails(Child)
------------------------------------------------------
ID ID status trade_id(Foreign Key
-------------------------------------------------------
1 1 New 1
2 Executed 1
Configuration configuration = new Configuration();
SessionFactory sessionFactory = configuration.configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
// 1.Parent.
Trade trade = new Trade();
// Child.
TradeDetails tDetails = new TradeDetails();
tDetails.setStatus("New");
tDetails.setTrade(trade); // Association
// Create a set of status
Set setOfStatus = new HashSet();
setOfStatus.add(tDetails);
// Add to Parent.
trade.setStatuses(setOfStatus);
session.save(trade);
transaction.commit();
// 2).Add a new Child record to an existing parent id.
trade = (Trade) session.load(Trade.class, 30);
// Child
TradeDetails tDet = new TradeDetails();
tDet.setStatus("Executed");
tDet.setTrade(trade);
setOfStatus.add(tDet);
trade.setStatuses(setOfStatus);
// Save child
session.saveOrUpdate(tDet);
session.flush();