删除父项时保留子项

时间:2014-05-06 12:53:28

标签: hibernate hibernate-mapping cascade

我目前面临以下问题:我在countriescities之间存在关联。正如您可能想象的那样,这种关系非常简单,country可以有多个cities,而city只属于一个country。删除country后,我希望将所有权cities保留在我的数据库中。

我的域名模型如下所示:

班级国家/地区

@Entity
@Table( name = "COUNTRIES" )
public class Country extends BaseEntity {
    private String name;
    private Set< City > cities = new HashSet<>();

    @Column( name = "NAME", length = 80, nullable = false, unique = true )
    public String getName() {
        return name;
    }

    public void setName( String name ) {
        this.name = name;
    }

    @OneToMany( fetch = FetchType.LAZY, mappedBy = "country", cascade = CascadeType.ALL )
    public Set< City > getCities() {
        return cities;
    }

    public void setCities( Set< City > cities ) {
        this.cities = cities;
    }
}

班级城市

@Entity
@Table( name = "CITIES" )
public class City extends BaseEntity {

    private String  name;
    private Country country;

    @Column( name = "NAME", length = 120, nullable = false )
    public String getName() {
        return name;
    }

    public void setName( String name ) {
        this.name = name;
    }

    @ManyToOne( fetch = FetchType.LAZY )
    @JoinColumn( name = "COUNTRY_ID", nullable = true )
    public Country getCountry() {
        return country;
    }

    public void setCountry( Country country ) {
        this.country = country;
    }
}

仅为了您的信息,BaseEntity只保留主键以及创建或修改实体时的信息。

如果从数据库中删除某个国家/地区,我如何才能删除我的城市?

1 个答案:

答案 0 :(得分:2)

替换cascade = CascadeType.ALL

cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH }

 @OneToMany( fetch = FetchType.LAZY, mappedBy = "country", cascade = CascadeType.ALL )
    public Set< City > getCities() {
        return cities;
    }