Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update or delete on table "users" violates foreign key constraint "fk_owner_id" on table "movie_list"

I have problem deleting a user and cascading deletion to all his movie lists.

class User {
    @OneToMany(mappedBy = "owner", cascade = CascadeType.REMOVE)
    @JsonIgnore
    private List<MovieList> movieLists;
}

class MovieList {
    @ManyToOne
    @JoinColumn(name = "owner_id", foreignKey = @ForeignKey(name = "fk_owner_id"))
    private User owner;
}

This is the method I call when trying to remove a user:

userRepository.delete(user);

When I try to delete a user, I get the following :

update or delete on table "users" violates foreign key constraint "fk_owner_id" on table "movie_list".

How can I solve it?

Thanks

like image 784
dpfaicchia Avatar asked Nov 04 '25 08:11

dpfaicchia


1 Answers

Hello i think you need add attributes in your anotation

Like this:

@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)

In other words, it has to pass (CascadeType.ALL, orphanRemoval = true)

like image 114
Andrey Rosa Avatar answered Nov 06 '25 23:11

Andrey Rosa