0

Author class:

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

Book class:

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

I want to delete author and i am getting following error: "update or delete on table "author" violates foreign key constraint "fk_book_author_fk" on table "book"". How can I delete author ? I want to delete author first, not book.

user123454321
  • 1,028
  • 8
  • 26

2 Answers2

1

By default, JPA does not cascade operations from parent to child entities. To enable this cascade from Author down to Book, change the following lines:

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

To:

@OneToMany(mappedBy = "author", cascade = CascadeType.ALL)
private List<Book> bookList;
Perception
  • 79,279
  • 19
  • 185
  • 195
0

author and book are related in the database and they have properties on delete which in your case can be cascade. You can change that to 'set Null' and perform the delete.

altsyset
  • 339
  • 2
  • 20