我正在使用 Spring Data 存储库来保存我的实体,但由于某种原因,级联不适用于测试 saveCountryAndNewCity() :城市没有得到保存,但它适用于类似的 saveCityAndNewCountry()。有人可以帮我弄清楚为什么吗?谢谢。
public class City {
@Cascade(CascadeType.ALL)
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "countryid", nullable = false, insertable = true, updatable = true)
private Country country;
public void setCountry(Country country) {
this.country = country;
country.getCities().add(this);
}
}
public class Country {
@Cascade(CascadeType.ALL)
@OneToMany(fetch = FetchType.EAGER, mappedBy = "country")
private Set<City> cities = new HashSet<City>(0);
public void addCity(City city){
this.cities.add(city);
city.setCountry(this);
}
}
@Test
@Transactional
public void saveCountryAndCity() throws Exception {
Country country = countryRepository.findOneByName("Canada");
City newCity = new City();
newCity.setName("Quebec");
country.addCity(newCity);
countryRepository.save(country);
}
@Test
public void saveCityAndNewCountry() throws Exception {
City city = cityRepository.findOneByName("London");
Country country = new Country();
country.setName("myCountry");
city.setCountry(country);
cityRepository.save(city);
}