我有一个ManyToMany关系,该关系分为2个OneToMany关系。一本书可以属于多个类别,一个类别可以包含多个书籍。
当我查询Book时,categories
列表只是空的。如何获得一本书所属的所有类别的列表?我想念什么吗?
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@NotBlank(message = "Please input book title")
private String title;
private Integer publishYear;
private String publisher;
private String language;
private Integer numberOfPages;
private String avatarUrl;
@OneToMany(targetEntity = BookCategory.class, cascade = CascadeType.ALL)
@JoinColumn(name = "category", nullable = false, insertable = false, updatable = false)
private Set<BookCategory> categories = new LinkedHashSet<>();
}
@Entity
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(nullable = false)
@NotBlank(message = "Please input category name")
private String name;
}
@Entity
public class BookCategory {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@ManyToOne
@JoinColumn(name = "book", nullable = false)
private Book book;
@ManyToOne
@JoinColumn(name = "category", nullable = false)
private Category category;
}
答案 0 :(得分:0)
尝试将mappedBy
属性与OneToMany关系的“一个”一侧的@OneTOMany注释一起使用。
或者您也可以尝试使用以下内容:
@ManyToMany
@JoinTable(
name = “book”_category,
joinColumns = @JoinColumn(name = “book_id”),
inverseJoinColumns = @JoinColumn(name = “category_id))
了解更多: https://vladmihalcea.com/the-best-way-to-use-the-manytomany-annotation-with-jpa-and-hibernate/