简体   繁体   中英

How to delete in spring-data-jpa in case of bi-directional mapping

I have country.java entity class with values and sources as the one to many associations. I have sources and values entity also which has the bi-directional mapping to country class with many to one.

Now I want to delete all the sources belonging to a particular country Id and all values for that country Id.

And after delete, I want to add a new set of values for both these fields.

If I just do

country.setcharValues(new ArrayList<>());
countryRepository.save(country);

It is deleting everything even the properties which I don't want to get deleted.

Country.Java

@OneToMany(mappedBy = "Country",cascade = { CascadeType.ALL},fetch = FetchType.EAGER,orphanRemoval = true)
@Fetch(value = FetchMode.SUBSELECT)
private List<Values> charvalues = new ArrayList<>();

@OneToMany(mappedBy = "Country",cascade = {CascadeType.ALL},fetch = FetchType.EAGER,orphanRemoval = true)
@Fetch(value = FetchMode.SUBSELECT)
private List<Property> charProperty = new ArrayList<>();

@OneToMany(mappedBy = "CharCountry",cascade = { CascadeType.ALL},fetch = FetchType.EAGER,orphanRemoval = true)
@Fetch(value = FetchMode.SUBSELECT)
private List<Source> charSource = new ArrayList<>();

If you want to clear all values and sources associated with Country , and then want to add new Values and Sources in same transaction, you can try something like below,

    final Country country = countryRepository.findById(countryId).get();

    country.getSources().clear();
    country.getValues().clear();
    countryRepository.saveAndFlush(country);

    // add new Values and Sources to country

    countryRepository.save(country);

As orphanRemoval = true is used, this should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM