我目前面临以下问题:我在countries
和cities
之间存在关联。正如您可能想象的那样,这种关系非常简单,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
只保留主键以及创建或修改实体时的信息。
如果从数据库中删除某个国家/地区,我如何才能删除我的城市?
答案 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;
}