[英]Entity unable to save foreign key Entities
我的Content
有一個Footnote
, Footnote
有content_id
列,它是Content
的外鍵。 不幸的是,用包含Footnote
的footnoteMap
保存我的Content
會引發以下錯誤:
ERROR: Cannot insert the value NULL into column 'content_id', table 'CMT_DEV.dbo.footnote'; column does not allow nulls. INSERT fails.
SEVERE: org.springframework.dao.DataIntegrityViolationException: Cannot insert the value NULL into column 'content_id', table 'CMT_DEV.dbo.footnote'; column does not allow nulls. INSERT fails.; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: Cannot insert the value NULL into column 'content_id', table 'CMT_DEV.dbo.footnote'; column does not allow nulls. INSERT fails.
我一定缺少進行這項工作所需的注釋,但是我無法弄清楚它是什么。
這是我的JPA映射:
public class Content implements EntityModel, Serializable {
@OneToMany(mappedBy="contentId", cascade=CascadeType.ALL)
@MapKey(name="number")
@OrderBy("number ASC")
private Map<Integer, Footnote> footnoteMap;
....
}
public class Footnote implements EntityModel, Serializable {
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name = "content_id", referencedColumnName= "id")
private Content contentId;
....
}
*更新*
請記住,添加Footnote
位置尚未保存內容項。
首先,請注意,將雙向關系的雙方保持一致狀態是您的責任,即,在向Content
添加Footnote
,還應適當設置其contentId
。
如果您這樣做了,但仍然失敗,則可能是數據庫模式與Hibernate映射之間不匹配。 注意, content_id
列具有非null約束,但是映射中沒有任何內容告訴Hibernate這樣的約束存在。 嘗試@ManyToOne(cascade=CascadeType.ALL, optional = false)
。
你需要有這樣的東西...
public void addFootnote(Footnote footnote) {
if (footnote == null) {
throw new IllegalArgumentException("Null argument not allowed");
}
footnote.setContent(this);
footNoteMap.put(<KEY_OF_MAP>, footnote);
}
這將確保為Footnote
實例填充content
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.