gpt4 book ai didi

java - Spring boot + jpa,通过表单提交进行多对多关联

转载 作者:太空宇宙 更新时间:2023-11-04 11:53:47 25 4
gpt4 key购买 nike

大家好,我刚刚开始学习 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 中是什么样子的?

最佳答案

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

关于java - Spring boot + jpa,通过表单提交进行多对多关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41533907/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com