Home > front end >  How to remove ManyToOne JPA object
How to remove ManyToOne JPA object

Time:01-11

I'm trying to remove object of child class without calling parent class so there's no need in 2 requests to database. Can you help to solve this problem and explain how to fix this.

Parent class:

@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private List<License> licenses;

Child class:

@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = "user_id", referencedColumnName = "id")
private Person user;

Trying to delete:

@Transactional
public void delete(License license) {
    licenseRepository.delete(license);
}

If I do CascadeType.ALL on Child (license) class, it removed parent class too. I need to remove only this license from database

CodePudding user response:

So here as i can see you have a parent class User and a child class License with a OneToMany Bi-Directional mapping.

Here in the Many side means in your License entity side, as long as you don't use the CascadeType.REMOVE, if you delete a license object it wont delete the user object.

so you can directly delete the license entry. It will look something like this:

licenseRepositoryObject.delete(licenseObjectToBeDeleted);

CodePudding user response:

Before deleting the child class using

  @Transactional
   public void delete(License license) {
   license.setUser(null);
  licenseRepository.delete(license);
    }

So that all relations between parent and child are removed

  • Related