【问题标题】:Spring boot + jpa, many to many association through form submissionspring boot + jpa,通过表单提交进行多对多关联
【发布时间】: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


    【解决方案1】:

    真正的问题是“连接表”有附加数据,例如出版商出版图书的日期、出版商图书的 ISBN 等等...... 如果答案是肯定的,那么它需要另一个表单,这可以解决您的问题,如果不是,您会从表单中收到您输入的图书的出版商列表,并通过书库... 从我的角度来看,数据库的设计缺乏信息。 当您回答该问题时,我会尽力帮助您以春天的方式来做... 目前从 db 的角度来看,在您需要现有对象的对象之间建立这种连接。 fromwise 的第一阶段是Publisher 的表单和Book 的表单。 众所周知,多对多令人头疼。 我建议在问题中添加 JPA 标签,并删除 spring-data

    【讨论】:

    • 非常感谢您的回答。@NiNiCkNaMe。 “连接表是否有附加数据”问题的答案是否定的。所以我需要有一个出版商的表格,然后在书的表格中我应该有出版商的名单?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-12
    • 1970-01-01
    • 2019-02-26
    • 2020-03-29
    • 2020-05-12
    相关资源
    最近更新 更多