简体   繁体   English

在一个实体中休眠OneToMany

[英]Hibernate OneToMany in one Entity

I try to create relationship in one entity (OneToMany in one table, parent - children relation) and I have a class: 我尝试在一个实体(一个表中的OneToMany,父-子关系)中创建关系,并且有一个类:

public class MenuItem {
@Id
@GeneratedValue
private long Id;
private String content;
private String name;

@ManyToOne(cascade = { CascadeType.ALL })
@JoinColumn(name="parent")
private MenuItem parent;

@OneToMany(cascade = CascadeType.ALL, mappedBy="parent")
private Set<MenuItem> childrens  = new HashSet<MenuItem>();

//getters and setters

}

Loading data works good but when I try to save MenuItem, i have following error: 加载数据效果很好,但是当我尝试保存MenuItem时,出现以下错误:

"Field 'childrens_id' doesn't have a default value" “字段'childrens_id'没有默认值”

Hibernate tries save in MenuItem correst values (I see it in logs), but, I think, its try to create another, Join table and finnaly transaction is failed. Hibernate尝试保存MenuItem Correst值(我在日志中看到它),但是,我认为,它尝试创建另一个Join表和最终事务失败。

This is exacly shows at: http://www.roseindia.net/hibernate/hibernate4/OnetoManySelfJoin.shtml but not working. 确实显示在: http ://www.roseindia.net/hibernate/hibernate4/OnetoManySelfJoin.shtml,但无法正常工作。 I used Hibernate 4.1.1 and Tomcat server 7. 我使用了Hibernate 4.1.1和Tomcat服务器7。

Solved : Drop and create database again. 解决 :删除并再次创建数据库。

guess best thing is to drop you database and run again. 猜测最好的办法是删除数据库,然后再次运行。 It seems you have hibernate/jpa impl setup to generate your database scheme, but the code and tables got too much out of synch. 看来您已经设置了hibernate / jpa impl设置来生成数据库方案,但是代码和表却太不同步了。 There is probably a field "dangling" in your table. 您的表中可能有一个字段“悬挂”。

As a side note: "Wild" guess: you had @JoinColumn(name="childrens_id") as a try before you changed it to the code above? 附带说明:“狂野”猜测:在将其更改为上面的代码之前,您尝试过@JoinColumn(name="childrens_id") (being confused with mappedBy values?) (是否与mappingBy值混淆?)

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

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