我有两个类。
public class Invoice {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "invoice_id", unique = true)
private int invId;
@OneToMany(mappedBy = "invoiceList", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
private List<Item> itemList;
@Column(name = "invoice_amt", nullable = false)
private Double invAmt;
}
并且,
public class Item {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "item_id", unique = true)
private int itemId;
@ManyToOne(optional = false, targetEntity = Invoice.class)
@JoinColumn(name="invoice_id")
private List<Invoice> invoiceList;
}
我是 JPA 新手。所以我的理解可能不准确。
我的理解是,如果我保存发票,该时刻的 invoice_id 应向下级联到所有项目的 invoice_id。
但是,我看到项目已保存,但项目的 invoice_id 被替换为 null
。
我错过了什么?
更新!!!更新!!!
好的,所以我将 @ManyToOne
更改为单一属性,并执行 objItem.setInvoice(objInvoice)
并保存它。但是,我在 invoice_id 上仍然得到 NULL
。
最佳答案
您正在注释多对一关系,但在两侧都使用集合。这是行不通的。一侧必须将关系映射到单一属性。在你的情况下,它将是
@ManyToOne
private Invoice invoice
也许您更需要多对多关系。在这种情况下,您需要将注释更改为 @ManyToMany
并摆脱级联(它们往往无法按多方的预期工作)。
targetEntity
属性和 @JoinColumn
注释在 Item
的 invoice
属性上是多余的。
为了让Item
保存相关发票的id,您首先需要设置Item
的invoice
属性,因为item 是拥有方(存储关系信息的一方)。
关于java - 对JPA感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25928449/