0
問題是可以在沒有級聯註釋的情況下在休眠中保存雙向關聯,從而避免瞬態對象異常。保存雙向關聯而不使用級聯
問題是可以在沒有級聯註釋的情況下在休眠中保存雙向關聯,從而避免瞬態對象異常。保存雙向關聯而不使用級聯
如果你不使用級聯,那麼你需要明確地保存這兩個實體。
entity1.setEntity(entity2)
entity2.setEntity(entity1)
session.save(entity1)
session.save(entity2)
您可以使用級聯= 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);