2014-05-06 152 views
0

我目前面临以下问题:我有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只需保持主键以及实体创建时的信息或改性。

如何从数据库中删除某个国家时,我的城市不会被删除?

回答

2

更换cascade = CascadeType.ALL

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

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

,我试过了,它看起来很有希望,但一旦我删除一个国家,我收到DataIntegrityViolationException因为外键没有相应的条目。所以我想我需要告诉Hibernate将'CITY.COUNTRY_ID'设置为null或-1? (仅供参考:'City'中的'@ JoinColumn'属性具有'nullable = true')。 – mhmpl

+1

@mhp这可能是由于你的城市仍然提到你的国家。你需要首先解除。 – mabi

+0

@mabi好的,我不确定Hibernate是否会为我做这件事。似乎没有。谢谢! – mhmpl

相关问题