我在同一个表中有父条目和子条目,为了区分我添加了一列具有父 ID。
表格说明如下
create table temp(id bigint(20) PK,name varchar(50),parent_id bigint(20) references temp(id));
例如..
id | name | parent_id
------------------------
1 | text1 | null
2 | text1.1 | 1
3 | text1.2 | 1
如何使用 hibernate save/saveOrUpdate 维护此表?
当我要在此表中保存记录时,它具有自动生成的 ID,因此在保存时我会得到 parent_id = 0 而不是实际 ID。
请给出一些必要的答案..
最佳答案
你可以在这里使用 hibernate 注释假设我有两个实体问题和答案。
Question have :
questionid
name
Answer have :
answerid
questionid
name
Answer Entity contain :
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="questionid")
private Question question;
Question Entiry contain :
@OneToMany(cascade=CascadeType.ALL,fetch=FetchType.LAZY,mappedBy="question")
private List<Answer> anserList = new ArrayList<Answer>();
现在您可以在实际创建问题之前设置答案,例如:
for(Answer opt : question.getAnswerList()){
opt.setQuestion(question);
}
关于mysql - 在hibernate中添加自表外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6304784/