5

I have the following two domain entities in my application:

public class City {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="CITY_ID")
private Long id;

@Column(name="CITY_NAME",length=20,nullable=false,unique=false)
private String cityName;

@ManyToOne(cascade={CascadeType.ALL})
@JoinColumn(name="COUNTRY_ID",nullable=false)
private Country country;
}



public class Country {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="COUNTRY_ID")
private Long id;

@Column(name="COUNTRY_NAME",length=20,nullable=false,unique=false)
private String countryName;

@OneToMany(mappedBy="country",cascade=CascadeType.ALL)
private Set<City> cities=new HashSet<City>();
}

Now I am facing a problem that whenever I delete any of the child records (Cities) parent country is also deleted.

So for example if I have country USA which have two cities (New York) and (California), now if I decided to delete (New York), I find that (California) and (USA) are also deleted! Which is wrong...so after some research I found that the problem is related to the Cascade I am using but didn't figure out what exactly I am doing wrong.

So can someone please advice what exactly I am doing wrong here? and how when I delete a city, I get it only deleted without its parent country?

Thanks for your time

4

1 回答 1

4

从实体country上的字段中删除级联。Citycascade元素指定在实体上执行操作时应在Country实体上执行哪些持久化操作City

public class City {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="CITY_ID")
private Long id;

@Column(name="CITY_NAME",length=20,nullable=false,unique=false)
private String cityName;

@ManyToOne
@JoinColumn(name="COUNTRY_ID",nullable=false)
private Country country;
}

如果您仍然需要级联其他操作,则需要在数组中指定每个操作。

public class City {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="CITY_ID")
private Long id;

@Column(name="CITY_NAME",length=20,nullable=false,unique=false)
private String cityName;

@ManyToOne(cascade={CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE})
@JoinColumn(name="COUNTRY_ID",nullable=false)
private Country country;
}

还要确保您没有在数据库中的外键上指定级联删除。

于 2013-08-15T00:32:56.593 回答