Hibernate ManyToMany删除/删除实体无法删除或更新父行:外键约束失败

时间:2014-08-10 18:29:52

标签: hibernate many-to-many

我在2个实体之间有一个ManyToMany关系。

作者 - > author_books< - 书籍。 共有3个表。

下面是代码:

@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;

现在,当我尝试执行以下操作时,出现以下错误:

BooksDao.delete(书籍); \ n 错误:无法删除或更新父行:外键约束失败(lucytestauthor_books,CONSTRAINT FK_d7blldnja6fa73ktxehccduq FOREIGN KEY(book_id)参考Booksbook_id))

我搜索整个网络和堆栈溢出但似乎无法找到答案。任何有此问题的人都会对任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:3)

我设法通过删除MySQL中的所有表并让hibernate这次只使用以下代码从头开始创建它来实现这一点:

@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;

我希望这能为每个人解除它给我带来的麻烦。