簡體   English   中英

如何使用Hibernate創建帶有嵌套對象的對象?

[英]How do I create an object with nested objects using Hibernate?

我收到以下異常:

Referential integrity constraint violation: "FK779B6FDFD4D56C1: PUBLIC.LOG_TAG FOREIGN KEY(PEOPLE_ID) REFERENCES PUBLIC.TAG(ID)";

這是我想做的事情:

Set<String> tagList = getTags();
Log log = new Log(content, user);
log.addTags(tagList);
log.save();

我認為可以理解該錯誤(嘗試通過引用尚未保存的對象來保存對象),但是我嘗試了保存每個對象的順序的所有組合,但似乎沒有任何效果。 我正在查看Play框架教程,以創建一個博客作為參考。 這是我的模型課:

@Entity
public class Log extends Model {
    @Lob
    public String content;

    @ManyToOne
    public User author;

    @ManyToMany(cascade=CascadeType.PERSIST)
    public Set<Tag> tags;

    public Log(String content, User author) {
        this.author = author;
        this.content = content;
        this.tags = new TreeSet<Tag>();
    }

    public void addTags(Set<String> tags) {
        for (String tag : tags) {
            Tag newTag = Tag.findOrCreateByName(tag); //since the DB is empty, this method is simply creating and .save()'ing tags
            this.tags.add(newTag);
        }
    }
}

現在,Tag類是一個只有一個字段的簡單實體。

我在這里做錯了什么? 我該如何工作?

您是否正在使用H2作為數據庫,並使用db = fs以便將其保存到文件系統? 您可以嘗試刪除db目錄,以便重新創建它。 由於您的錯誤消息引用了PEOPLE_ID,並且示例中沒有“ people”字段,因此該架構看起來與模型不同步。

要查看出了什么問題,您可以打開休眠的sql查詢的輸出,然后在保存日志之前查看是否真正保存了標簽

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM