Hibernate ManyToMany object delete / delete Unable to delete or update parent row: foreign key constraint fails
I have a ManyToMany relationship between two objects.
Author -> author_books <- Books. A total of 3 tables.
Below is the code:
@Entity
public class Author
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "author_id")
private Long author_id;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "Author_Books", joinColumns = @JoinColumn(name = "author_id"), inverseJoinColumns = @JoinColumn(name = "book_id"))
private List<Books> books;
@Entity
@Table(name = "Books")
public class Books
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "book_id")
private Long book_id;
@ManyToMany(mappedBy = "books")
@NotNull
private List<Author> authors;
Now when I try to do the following I get the following error:
<strong> BooksDao.delete (books); \ n ERROR: unable to delete or update parent row: foreign key constraint fails ( lucytest
. author_books
, CONSTRAINT FK_d7blldnja6fa73ktxehccduq
FOREIGN KEY ( book_id
) REFERENCES Books
( book_id
))
I go through the whole pause and stack overflow but can't seem to find an answer. Any help would be appreciated also for anyone else having this problem.
source to share
I managed to get this working by dropping all tables in MySQL and letting hibernate create them from scratch just this time with the following code:
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "Author_Books", joinColumns = @JoinColumn(name = "author_id"), inverseJoinColumns = @JoinColumn(name = "book_id"))
@Valid
private List<Books> books;
@ManyToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.DETACH})
@JoinTable(name = "Author_Books", joinColumns = @JoinColumn(name = "book_id"), inverseJoinColumns = @JoinColumn(name = "author_id"))
@Valid
private List<Author> authors;
Hope this saves everyone that gave me the headache.
source to share