I'm using Spring Data repository to save my entities, but for some reason the cascade doesn't work for the test saveCountryAndNewCity() : the city doesn't get saved but it works for saveCityAndNewCountry() which is similar. Can someone help me to figure out why? Thx.
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);
}