大家好我刚刚开始学习弹簧靴,并想知道如何通过表单提交保存多对多关系的对象?
说我们有两个图书和出版商实体
@Entity
public class Book{
private long id;
private String name;
private List<Publisher> publishers;
public Book() {
}
public Book(String name) {
this.name = name;
}
public Book(String name, Set<Publisher> publishers){
this.name = name;
this.publishers = publishers;
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "book_publisher", joinColumns = @JoinColumn(name = "book_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "publisher_id", referencedColumnName = "id"))
public List<Publisher> getPublishers() {
return publishers;
}
public void setPublishers(List<Publisher> publishers) {
this.publishers = publishers;
}
}
@Entity
public class Publisher {
private Long id;
private String name;
private List<Book> books;
public Publisher(){
}
public Publisher(String name){
this.name = name;
}
public Publisher(String name, List<Book> books){
this.name = name;
this.books = books;
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ManyToMany(mappedBy = "publishers")
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
}
然后我们有一个图书库
public interface BookRepository extends CRUDRepository<Book, Long>{
}
如何在bookcontroller中使用crud方法?
答案 0 :(得分:0)
真正的问题是“连接表”有附加数据,例如发布者出版书籍的日期,该出版商的书籍ISBN等等......
如果答案是肯定的,那么它需要另一个表格,这解决了您的问题,如果没有,您从您输入的图书的出版商的表单列表中收到,并将它们分别添加到连接表和书籍到书表通过书库...
从我的角度来看,数据库的设计缺乏信息。
当你回答这个问题的时候,我会试着帮你做春天的事......
当前从db的角度来看,在需要现有对象的对象之间进行这种连接。而fromwise的第一个阶段是Publisher
的形式和Book
的形式。
众所周知,许多人都很头疼。
我建议在问题中添加JPA
标记,然后删除spring-data
。