孩子也在休眠时删除父母及其孩子

时间:2016-01-26 16:06:30

标签: hibernate jpa

我正在使用country-> State(OTM) - >使用hibernate的区域(OTM)关系。

我面临的问题是当我尝试删除单个状态时,

1)它删除所有国家,其父母(国家)和所有(相关和无关)儿童(地区)。
OR
2)没有删除任何内容

我在谷歌花了很多时间但却无法解决。有人能帮帮我吗?

以下是我在实体层面的关系。我在 StateMaster 实体(例如

)尝试了不同的级联类型组合

1)@ManyToOne(cascade=CascadeType.ALL) - 删除国家,州和所有地区(与州相关且无关)
2)@ManyToOne(cascade=CascadeType.REFRESH) - 不删除国家,州和地区
3)@ManyToOne(cascade=CascadeType.MERGE) - 不删除国家,州和地区
4)@ManyToOne(cascade=CascadeType.REMOVE) - 删除国家,州和所有地区(与州有关和无关)
5)@ManyToOne(cascade=CascadeType.PERSIST) - 不删除国家,州和地区
6)@ManyToOne(cascade=CascadeType.DETACH) - 不删除国家,州和地区

@SQLDelete(sql="UPDATE country_master SET delete_ind = 'Y' WHERE country_id = ?")
@Where(clause="delete_ind is NULL")
public class CountryMaster implements Serializable {
    //bi-directional many-to-one association to StateMaster
    @OneToMany(mappedBy="countryMaster", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
    @Where(clause="delete_ind is NULL")
    private List<StateMaster> stateMasters;
}


@SQLDelete(sql="UPDATE state_master SET delete_ind = 'Y' WHERE state_id =   ?")
@Where(clause="delete_ind is NULL")
public class StateMaster implements Serializable {
    //bi-directional many-to-one association to DistrictMaster
    @OneToMany(mappedBy="stateMaster", cascade=CascadeType.ALL)
    @Where(clause="delete_ind is NULL")
    private List<DistrictMaster> districtMasters;

    //bi-directional many-to-one association to CountryMaster
    @ManyToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="country_id", updatable=false)
    private CountryMaster countryMaster;
}


@SQLDelete(sql="UPDATE district_master SET delete_ind = 'Y' WHERE dist_id = ?")
@Where(clause="delete_ind is NULL")
public class DistrictMaster implements Serializable {
    //bi-directional many-to-one association to Address
    @OneToMany(mappedBy="districtMaster",cascade=CascadeType.ALL)
    private List<Address> addresses;

    //bi-directional many-to-one association to StateMaster
    @ManyToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="state_id")
    private StateMaster stateMaster;
}


@Transactional(value="adminTransactionManager")
public MasterDataBean deleteCountryStateDist(MasterDataBean masterDataBean, String countryCode,String stateCode,String distCode) {
    ..........
    ...........
    else if(StringUtils.isNotEmpty(stateCode)) {
        StateMaster state = stateMasterRepository.findByStateCode(stateCode);
        if(state == null) {
            if(log.isDebugEnabled()) {
                log.error("State does not exists");
            }
            masterDataBean.setErrorMsg("State does not exists for state code: " + stateCode);
            return masterDataBean;
        }

        stateMasterRepository.delete(state);
    }
}

请注意: 我在我的代码中实现了软删除。因此,在删除时,它会将delete_ind标志更新为“Y”

0 个答案:

没有答案