Spring boot Spring数据JPA填充2个一对多关系的数据
我有很多的关系,可以分解成两个一个一个的关系。一本书可以属于多个类别,一个类别可以有多本书。 当我查询图书时,Spring boot Spring数据JPA填充2个一对多关系的数据,spring-boot,spring-data-jpa,Spring Boot,Spring Data Jpa,我有很多的关系,可以分解成两个一个一个的关系。一本书可以属于多个类别,一个类别可以有多本书。 当我查询图书时,categories列表变为空。如何获得一本书所属的所有类别的列表?我错过什么了吗 @Entity public class Book { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; @NotBlank(message = "Please input 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;
}
@实体
公共课堂用书{
@身份证
@GeneratedValue(策略=GenerationType.AUTO)
私有整数id;
@NotBlank(message=“请输入书名”)
私有字符串标题;
私人整数出版年;
私有字符串发布器;
私有字符串语言;
私有整数页数;
私有字符串;
@OneToMany(targetEntity=BookCategory.class,cascade=CascadeType.ALL)
@JoinColumn(name=“category”,nullable=false,insertable=false,updateable=false)
私有集类别=新LinkedHashSet();
}
@实体
公共类类别{
@身份证
@GeneratedValue(策略=GenerationType.AUTO)
私有整数id;
@列(nullable=false)
@NotBlank(message=“请输入类别名称”)
私有字符串名称;
}
@实体
公共类图书类别{
@身份证
@GeneratedValue(策略=GenerationType.AUTO)
私有整数id;
@许多酮
@JoinColumn(name=“book”,nullable=false)
私人书籍;
@许多酮
@JoinColumn(name=“category”,nullable=false)
私人类别;
}
尝试使用mappedBy
属性,在OneTOMany关系的“一侧”使用@OneTOMany注释
或者,您也可以尝试使用以下方法:
@ManyToMany
@JoinTable(
name = “book”_category,
joinColumns = @JoinColumn(name = “book_id”),
inverseJoinColumns = @JoinColumn(name = “category_id))
阅读更多: