I have use case, a Book has one Category and a Category could belong to a lot of Books. One Book could belong to multi Authors and an Author could belong to multi books. So, here is their relationship:
BooktoBookCategory=>many-to-oneBookCategorytoBook=>one-to-manyBooktoAuthorandAuthortoBook=>many-to-many
So, I have 4 table:
bookbook_categoryauthorbook_author(book_id,author_id)
Case:
- if I delete a
Book, there should nothing happen to thebook_categorytable - If I delete a
Book, theAuthorshould be deleted if theAuthornot belong to anybooksanymore. For example, I havebook1andbook2with sameAuthornamedJohn. If I deletebook1, it wont deleteJohn. But if I deletebook2also, thenJohnwill be deleted fromAuthortable. Also, any book deletion will affectbook_authortable.
here is how I declare the entity
Author
@Entity(name = "author")
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name", nullable = false)
private String name;
@Column(name = "address", nullable = false)
private String address;
@ManyToMany(mappedBy = "author", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JsonBackReference
private Set<Book> book;
}
Book
@Entity(name = "book")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "title", nullable = false)
private String title;
@Column(name = "year", nullable = false)
private String year;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(
name = "book_author",
joinColumns = @JoinColumn(name = "book_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "author_id", referencedColumnName = "id"))
@JsonManagedReference
private Set<Author> author;
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "category_id", referencedColumnName = "id", nullable = false)
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
private BookCategory category;
}
Book Category
@Entity(name = "book_category")
public class BookCategory {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "category", nullable = false)
private String category;
}
and here is how I try to delete the book. Just a simple method. But, after I run this, it show error said org.postgresql.util.PSQLException: ERROR: update or delete on table "book_category" violates foreign key constraint "fk5jgwecmfn1vyn9jtld3o64v4x" on table "book", which seems like the method try to also delete the book_category table.
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public ResponseEntity<?> delete(@PathVariable(value = "id") Long id) throws Exception {
try {
bookService.deleteById(id);
return ResponseEntity.ok().body("delete done");
} catch (Exception e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
}
Then, how to achieve it? Any clue, please?