我有Book桌子和Author桌子。他们的关系是many-to-many。
我的目标
我希望能够坚持新书。如果书籍的作者已经存在于Author表中,我不想在Author表中保留相同的作者。如果作者在表中不存在Author,则作者数据将保留在Author表中。以下是我声明实体和 serviceImplementation 以保存数据的方式:
书
@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;
}
作者
@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;
}
如果所有作者都存在于Author表中或表中根本不存在,则上面的代码是有效的Author。如果其中一个存在而另一个不存在,它将根据CascadeType我在定义实体时使用的错误抛出错误。
慕尼黑的夜晚无繁华
相关分类