我遇到以下异常:
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”字段。
关于java - 如何使用 Hibernate 创建具有嵌套对象的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8158833/