简体   繁体   English

实体无法保存外键实体

[英]Entity unable to save foreign key Entities

My Content has a Map of Footnote , and Footnote has a content_id column which is a foreign key back to Content . 我的Content有一个FootnoteFootnotecontent_id列,它是Content的外键。 Unfortunately saving my Content with the footnoteMap containing a Footnote throws the following error: 不幸的是,用包含FootnotefootnoteMap保存我的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.

I must be missing something with the annotations required to make this work, but I can't figure out what it is. 我一定缺少进行这项工作所需的注释,但是我无法弄清楚它是什么。

Here is my JPA mapping: 这是我的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;

    ....
}

* update * *更新*

Keep in mind that the point at which a Footnote is added, the content item has not been saved. 请记住,添加Footnote位置尚未保存内容项。

First of all, note that it's your responsibility to keep both sides of bidirectional relationships in consitent state, ie when you add a Footnote to Content you should also set its contentId appropriately. 首先,请注意,将双向关系的双方保持一致状态是您的责任,即,在向Content添加Footnote ,还应适当设置其contentId

If you did so but it still fails, then perhaps it's a mismatch between database schema and Hibernate mapping. 如果您这样做了,但仍然失败,则可能是数据库模式与Hibernate映射之间不匹配。 Note that content_id column has a not null constraint, but nothing in the mapping tells Hibernate that such a constraint exists. 注意, content_id列具有非null约束,但是映射中没有任何内容告诉Hibernate这样的约束存在。 Try @ManyToOne(cascade=CascadeType.ALL, optional = false) . 尝试@ManyToOne(cascade=CascadeType.ALL, optional = false)

You need to have something like this... 你需要有这样的东西...

public void addFootnote(Footnote footnote) {
    if (footnote == null) {
        throw new IllegalArgumentException("Null argument not allowed");
    }
    footnote.setContent(this);
    footNoteMap.put(<KEY_OF_MAP>, footnote);
}

which will make sure that content is populated for Footnote instance. 这将确保为Footnote实例填充content

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM