无需使用级联即可保存双向关联

时间:2017-03-08 11:44:44

标签: hibernate

问题是可以在没有级联注释的情况下在休眠中保存双向关联,从而避免瞬态对象异常。

2 个答案:

答案 0 :(得分:1)

如果您不使用级联,则需要明确保存两个实体。

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

答案 1 :(得分:0)

您可以将 cascade = 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);