2017-03-08 98 views

回答

1

如果你不使用級聯,那麼你需要明確地保存這兩個實體。

entity1.setEntity(entity2) 
entity2.setEntity(entity1) 
session.save(entity1) 
session.save(entity2) 
0

您可以使用級聯= CascadeType.ALL

@Entity 
    @Table(name = "invoice") 
    public class Invoice { 

     @Id 
     @GeneratedValue(strategy = GenerationType.AUTO) 
     @Column(name = "id") 
     private int id; 

     @Column(name = "invoice_date") 
     @Temporal(TemporalType.TIMESTAMP) 
     private Date invoiceDate; 

     @Column(name = "customer") 
     private String customer; 

     @OneToMany(fetch = FetchType.EAGER, mappedBy = "itemPk.invoice", cascade = CascadeType.ALL) 
     private List<InvoiceItem> invoiceItems; 
.... 

} 

這樣的話在你的代碼,

InvoiceDao invoiceDao = new InvoiceDao(); 
Invoice invoice = new Invoice(); 
invoice.setInvoiceDate(new Date()); 
invoice.setCustomer("Sameera"); 

InvoiceItem invoiceItem1 = new InvoiceItem(); 
invoiceItem1.setQty(10); 
invoiceItem1.setPrice(100.10d); 

InvoiceItemPK itemPk1 = new InvoiceItemPK(); 
itemPk1.setInvoice(invoice); 
itemPk1.setItem(item); 
invoiceItem1.setItemPk(itemPk1); 

List<InvoiceItem> items = new ArrayList<>(); 
items.add(invoiceItem1); 
invoice.setInvoiceItems(items); 
invoiceDao.save(invoice);