此方法用于保存父母和子女:
public Response createMultipleChilds(PurchaseOrderHeader purchaseOrderHeader){
try {
s=sf.openSession();
tx=s.beginTransaction();
createParent(purchaseOrderHeader);
for(int i=0;i<purchaseOrderHeader.getPurchaseItemList().size();i++){
purchaseOrderHeader.getPurchaseItemList().get(i).setHeaderDetails(purchaseOrderHeader);
createChild(purchaseOrderHeader.getPurchaseItemList().get(i));
}
response.setStatus(200);
response.setMessage(" both added succesfull");
if(tx.isActive()){
tx.commit(); }
} catch (Exception e) {
System.err.println("Exception : " + e.getMessage());
response.setStatus(500);
response.setMessage("parent not added");
tx.rollback();
}finally{
s.close();
}
return response;
}
此方法被调用以保存父属性:
private void createParent(PurchaseOrderHeader purchaseOrderHeader) {
try {
s=sf.openSession();
tx=s.beginTransaction();
PurchaseOrderHeader order=new PurchaseOrderHeader();
if(purchaseOrderHeader.getCompany_code() instanceof String)
order.setCompany_code(purchaseOrderHeader.getCompany_code());
if(purchaseOrderHeader.getCurrency() instanceof String)
order.setCurrency(purchaseOrderHeader.getCurrency());
if(purchaseOrderHeader.getStatus() instanceof String)
order.setStatus(purchaseOrderHeader.getStatus());
if(purchaseOrderHeader.getVendor() instanceof String)
order.setVendor(purchaseOrderHeader.getVendor());
order.setPurchaseItemList(null);
order.setDocument_number(purchaseOrderHeader.getDocument_number());
s.save(order);
response.setStatus(200);
response.setMessage(" parent added succesfull");
if(tx.isActive()){
tx.commit(); }
} catch (Exception e) {
System.err.println("Exception : " + e.getMessage());
response.setStatus(500);
response.setMessage("parent not added");
tx.rollback();
}
finally{
s.close();
}
}
调用此方法来存储子对象:
private void createChild(PurchaseItem purchaseItem) {
try {
s=sf.openSession();
tx=s.beginTransaction();
PurchaseItem item=new PurchaseItem();
if(purchaseItem.getItemName() instanceof String)
item.setItemName(purchaseItem.getItemName());
if(purchaseItem.getItemPrice() instanceof String)
item.setItemPrice(purchaseItem.getItemPrice());
item.setHeaderDetails(purchaseItem.getHeaderDetails());
s.save(item);
response.setStatus(200);
response.setMessage(" child added succesfull");
if(tx.isActive()){
tx.commit(); }}
catch (Exception e) {
System.err.println("Exception : " + e.getMessage());
response.setStatus(500);
response.setMessage("child not added");
tx.rollback();
}
finally{
s.close();
}
}
该方法同时存储父级和子级,但未验证(意味着当我传递int值而不是字符串时,即使我正在检查数据类型,它也会被存储)