我在智利实体类中的 Parent 和对应的 ManyToOne 中提供了一个简单的 oneToMany 关系:
家长:
@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
对于任何操作:新的插入或删除或更新,它首先将旧数据复制到数据库,然后是我执行的操作。