【发布时间】:2017-05-22 21:08:54
【问题描述】:
大家好,我刚开始学习 Spring Boot,想知道如何通过表单提交保存具有多对多关系的对象?
假设我们有书籍和出版商两个实体
@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>{
}
crud 方法在 bookcontroller 中会是什么样子?
【问题讨论】:
标签: java jpa spring-boot