@ManyToOne,@ OneToMany删除错误

时间:2013-02-01 12:59:23

标签: java database jpa one-to-many many-to-one

作者类:

@Id
@GeneratedValue(
        strategy = GenerationType.AUTO)
private int id;
private String firstName;
private String lastName;
@OneToMany(
        mappedBy = "author")
private List<Book> bookList;

图书课程:

@Id
@GeneratedValue(
        strategy = GenerationType.AUTO)
private int id;
private String name;
private String language;
private int isbn;
@ManyToOne
@JoinColumn(
        name = "author_fk")
private Author author;

我想删除作者并且我收到以下错误:“更新或删除表”作者“违反了表”book“”上的外键约束“fk_book_author_fk”。如何删除作者?我想首先删除作者,而不是预订。

2 个答案:

答案 0 :(得分:1)

默认情况下,JPA不会将操作从父实体级联到子实体。要从Author向下Book启用此级联,请更改以下行:

@OneToMany(mappedBy = "author")
private List<Book> bookList;

要:

@OneToMany(mappedBy = "author", cascade = CascadeType.ALL)
private List<Book> bookList;

答案 1 :(得分:0)

作者和书籍在数据库中是相关的,它们具有删除属性,在您的情况下可以级联。您可以将其更改为“设置为空”并执行删除。