我得到以下异常:如何使用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 Framework教程。这是我的模型类:
@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);
}
}
}
现在,标记类是一个简单的实体,只有一个字段。
我在这里做错了什么?我如何完成这项工作?
你的数据库有些奇怪。该异常表示LOG_TAG表具有TAG.ID的外键(PEOPLE_ID)。无论您需要删除并重新创建表格,还是映射存在问题。 Model的名称为“PEOPLE_ID”的@Id列? – sceaj