我在Parent中提供了一个简单的oneToMany关系,并在Chile Entity类中提供了相应的ManyToOne:
家长:
@Entity
@Table(name = "FormExtraInfo")
@PrimaryKeyJoinColumn(name="form_container_id")
public class Form extends Container {
private List<Reason> reasons = new ArrayList<Reason>();
@OneToMany(mappedBy="form",cascade={javax.persistence.CascadeType.ALL},orphanRemoval=true)
@Cascade(value={CascadeType.ALL})
public List<Reason> getReasons() {
return reasons;
}
public void setReasons(List<Reason> reasons) {
this.reasons = reasons;
}
public void addReason(Reason reason) {
if (this.reasons == null) {
this.reasons = new ArrayList<Reason>();
}
this.reasons.add(reason);
}
}
儿童班:
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="Container_id")
public Form getForm() {
return form;
}
public void setForm(Form form) {
this.form = form;
}
动作类:
//Set the reasons
String[] reasonStatus = strutsForm.getMultiValueProperty(REASON_STATUS);
String[] reasonText = strutsForm.getMultiValueProperty(REASON_TEXT);
List<Reason> reasons = new ArrayList<Reason>();
logger.debug("form container ID : " + form.getId() +". # of Reasons for this form: "+ reasonText.length);
for (int i = 0; i < reasonText.length; i++) {
Reason r = new Reason();
r.setComment(reasonText[i]);
r.setStatusTypeCode(reasonStatus[i]);
r.setForm(form);
reasons.add(r);
}
form.setReasons(reasons);
示例案例: Status_code Reason_text abc abc1 xyz xyz1
保存表单: Status_code Reason_text abc abc1 xyz xyz1 abc abc1 xyz xyz1
对于任何操作:新插入或删除或更新,它首先将旧数据复制到数据库,然后复制我执行的操作。
答案 0 :(得分:0)
尝试替换此
的cascade子句@Cascade (value={CascadeType.SAVE_UPDATE,CascadeType.DELETE_ORPHAN})
查看关于映射一对多http://arecordon.blogspot.com.ar/2013/05/hibernate-mapping-associations-one-to_20.html
的博客文章答案 1 :(得分:0)
如果您可以使用Set而不是List;然后,尝试将集合更改为Set,并确保覆盖equals()hashCode(),如下所示:
https://community.jboss.org/wiki/EqualsAndHashCode?_sscc=t
另外,删除重复的级联,你可以使用:
@OneToMany(mappedBy="form",cascade={javax.persistence.CascadeType.ALL},orphanRemoval=true)
或
@OneToMany(mappedBy="form")
@Cascade(value={CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN})