0

I have the following entities (only relevant parts are shown):

@Entity
@Table(name = "foo", schema = "public", catalog = "mycatalog")
public class Foo {
    private Integer id;
    private Collection<Bar> bars;
   
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @OneToMany(mappedBy = "foo", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    public Collection<Bar> getBars() {
        return bars;
    }

    public void setBars(Collection<Bar> bars) {
        this.bars= bars;
    }
}

@Entity
@Table(name = "bar", schema = "public", catalog = "mycatalog")
public class Bar{
    private Integer id;
    private Foo foo;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @ManyToOne(cascade=CascadeType.DETACH)
    @JoinColumn(name = "foo", referencedColumnName = "id", nullable = false)
    public Foo getFoo() {
        return foo;
    }

    public void setFoo(Foo foo) {
        this.foo = foo;
    }
}

In the database, the table "bar" has a foreign key referencing a foo id. The table "foo" does not hold any bars itself.

This works as far as when I save a Foo to the database using fooService.update(foo), the Bars in its collection are saved as well. I am using Spring Boot, the fooService is an autowired FooService and itself contains and autowired FooRepository.

In some part of my code, I use foo.getBars().clear(), then add some other bars, and then fooService.update(foo).

I was wondering if there is a way to automatically delete the bars from the database that have been cleared from the collection once I update my foo? Of course I could do that manually before I clear the collection, but it would be very nice if I wouldn't have to do that.

maddingl
  • 197
  • 4
  • 20
  • 1
    Does this answer your question? [JPA OneToMany not deleting child](https://stackoverflow.com/questions/2011519/jpa-onetomany-not-deleting-child) – Osama A.Rehman Mar 18 '21 at 06:30

1 Answers1

1

You can use orphanRemoval in your OneToMany annotation

@OneToMany(mappedBy = "foo", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)

When you remove elements in getBars() collection and save the Foo, the underlying records in DB also get removed

Hưng Chu
  • 1,027
  • 5
  • 11