2

我在智利实体类中的 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

对于任何操作:新的插入或删除或更新,它首先将旧数据复制到数据库,然后是我执行的操作。

4

2 回答 2

0

尝试为此替换级联子句

@Cascade (value={CascadeType.SAVE_UPDATE,CascadeType.DELETE_ORPHAN})

看看我关于映射一对多的博客文章http://arecordon.blogspot.com.ar/2013/05/hibernate-mapping-associations-one-to_20.html

于 2013-08-09T02:21:16.390 回答
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})
于 2013-08-09T17:38:38.043 回答