Hibernate:关于父子关系的更新会导致重复的子项

时间:2010-05-06 21:25:33

标签: hibernate spring-mvc

我有一个父子关系,其中父母有一个子集合(一个特定的集合)。使用cascade =“all-delete-orphan”设置子集合。当我最初保存父元素时,一切都按预期工作。但是,当我更新父级并再次保存时,将重新保存所有子级。

这种行为让我相信父母正在失去对孩子集合的引用,因此当坚持所有孩子时,他们会被重新保存。似乎修复此问题的唯一方法是不使用此子集合的setter方法,但遗憾的是,我的应用程序中隐式调用此setter(Spring MVC用于将多选表单元素绑定到此集合,以及setter在表格提交上被春天调用。覆盖此setter以不丢失引用(即,执行colleciton.clear()和collection.addAll(newCollection)而不是collection = newCollection)显然是一个休眠禁忌,如此处所指出的:https://forum.hibernate.org/viewtopic.php?t=956859

有谁知道如何规避这个问题?我在下面发布了一些代码。

父hibernate配置:

<hibernate-mapping package="org.fstrf.masterpk.domain">
<class name="ReportCriteriaBean" table="masterPkReportCriteria">

    <id name="id" column="id">
        <generator class="org.hibernate.id.IncrementGenerator" />
    </id>

    <set name="treatmentArms" table="masterPkTreatmentArms" 
         sort="org.fstrf.masterpk.domain.RxCodeComparator" lazy="false" cascade="all-delete-orphan" inverse="true">
        <key column="runid"/>
        <one-to-many class="TreatmentArm"/>
    </set>
</class>
</hibernate-mapping>

父对象:

public class ReportCriteriaBean{

    private Integer id;
    private Set<TreatmentArm> treatmentArms;

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }

    public Set<TreatmentArm> getTreatmentArms() {
        return treatmentArms;
    }
    public void setTreatmentArms(Set<TreatmentArm> treatmentArms) {
        this.treatmentArms = treatmentArms;
        if(this.treatmentArms != null){
        for(TreatmentArm treatmentArm : this.treatmentArms){
            treatmentArm.setReportCriteriaBean(this);
        }
    }
}

子休眠配置:

<hibernate-mapping package="org.fstrf.masterpk.domain">
    <class name="TreatmentArm" table="masterPkTreatmentArms">
        <id name="id" column="id">
            <generator class="org.hibernate.id.IncrementGenerator" />
        </id>

        <many-to-one name="reportCriteriaBean" class="ReportCriteriaBean" column="runId" not-null="true" />

        <property name="rxCode" column="rxCode" not-null="true"/>
    </class>
</hibernate-mapping>

子对象:

public class TreatmentArm {

    private Integer id;
    private ReportCriteriaBean reportCriteriaBean;
    private String rxCode;

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public ReportCriteriaBean getReportCriteriaBean() {
        return reportCriteriaBean;
    }
    public void setReportCriteriaBean(ReportCriteriaBean reportCriteriaBean) {
        this.reportCriteriaBean = reportCriteriaBean;
    }
    public String getRxCode() {
        return rxCode;
    }
    public void setRxCode(String rxCode) {
        this.rxCode = rxCode;
    }
}

1 个答案:

答案 0 :(得分:0)

它可能来自Hibernate Bug