我使用hibernate和spring数据来保存数据库中的实体。我将子元素附加到父元素,反之亦然。一切都在数据库中正确保存,以及子实例。
再次调用save方法后,子元素将被保存两次。我发现,原因是,该框架在持续存在后不会更新子项ID。它始终为零。父ID已正确更新。
知道如何解决这个问题吗?
Receipt.java:
@Entity
@javax.persistence.Table(name = "receipts")
public class Receipt {
private int id;
/*
* [...]
*/
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@OneToMany(fetch = FetchType.EAGER,cascade = CascadeType.ALL)
@JoinColumn(name = "receipt_id",referencedColumnName = "id")
private List<ReceiptItem> getReceiptItemList() {
return receiptItemList;
}
private void setReceiptItemList(List<ReceiptItem> receiptItemList) {
this.receiptItemList = receiptItemList;
}
/*
* [...]
*/
}
ReceiptItem.java:
@Entity
@Table(name = "receipt_items")
public class ReceiptItem {
private int id;
/*
* [...]
*/
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "receipt_id")
public Receipt getReceipt() {
return receipt;
}
public void setReceipt(Receipt receipt) {
this.receipt = receipt;
}
}
存储
item = new ReceiptItem();
item.setReceipt(receipt);
receipt.getReceiptItemList().add(item);
// this should create the new ReceiptItem instance
receiptService.save(receipt);
System.out.println("ItemId: "+item.getId()); //but the id is still 0
// calling save method twice results in a second entry in the database
// instead of updating the previously inserted one
receiptService.save(receipt);
System.out.println("ItemId: "+item.getId());
输出:
ItemId: 0
ItemId: 0