Search code examples
spring-data-jpaspring-data

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?


Solution

  • 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<>();