RamPrakash
RamPrakash

Reputation: 3254

Spring-Data-JPA - How to delete child record in OneToMany relationship

I have a Person entity which has Set<Address> with OneToMany mapping.

@OneToMany(
        mappedBy = "person",
        fetch = FetchType.LAZY,
        cascade = CascadeType.ALL
)
private Set<Address> addresses = new HashSet<>();

Address class has

@ManyToOne
@JoinColumn(name = "person_id")
private Person person;

Now I am able to add records in the DB successfully.

How can I achieve the clearing the address hashset should result to removing the address records for the person.

For ex: In my service layer, below code does not remove the addresses in the DB.

Person p =  personRepository.findBy(1).get();
p.getAddresses().clear();
personRepository.save(p);

What is the right way to achieve this?

Upvotes: 2

Views: 11547

Answers (3)

Surabhi Bhawsar
Surabhi Bhawsar

Reputation: 39

orphanRemoval attribute handles child entities removal with parent entity.

@OneToMany(mappedBy="class", 
           cascade= {CascadeType.PERSIST, CascadeType.REMOVE}, 
           orphanRemoval=true)
Set<ClassStudents> students;

OR

@OneToMany(mappedBy="class", 
           cascade= CascadeType.ALL, 
           orphanRemoval=true)
Set<ClassStudents> students;

Upvotes: 4

Mirko Brandt
Mirko Brandt

Reputation: 475

Normally if you want to remove a child from the parent class you should do this by deleting the record of your child class. In this instance you would delete the addresses in the addressRepository:

Person p =  personRepository.findBy(1).get();
addressRepository.deleteAll(p.getAddresses());

Upvotes: 0

RamPrakash
RamPrakash

Reputation: 3254

I had to do this to make this work.

@OneToMany(
        mappedBy = "person",
        fetch = FetchType.LAZY,
        cascade = CascadeType.ALL,
        orphanRemoval = true
)
private Set<Address> addresses = new HashSet<>();    

Upvotes: 6

Related Questions