2017-01-08 98 views
1

嗨,大家好,我剛剛開始學習春季啓動,想知道如何通過表單提交保存多對多關係的對象?春季引導+ jpa,多對多協會通過表單提交

說我們的書和出版商

@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的?

回答

0

真正的問題是「連接表」有附加數據,例如日期由出版商出版該書,該出版商出版的書的ISBN等等...... 如果答案是肯定的,那麼它需要另一種形式,並且解決了您的問題,如果沒有,您從您輸入的圖書的出版商的表單列表中獲得並分別將它們添加到連接表和書籍通過圖書庫存儲到書形表中... from我的觀點是數據庫的設計缺乏信息。 當你將回答這個問題,生病試圖幫助你做到這一點春天... currenly從數據庫的角度來做這樣的對象之間的連接,你需要現有的對象。並且第一階段從Publisher形成,並且形式爲Book。衆所周知,許多人都很頭疼。 我建議將JPA標記添加到問題中,並刪除spring-data

+0

非常感謝你的回答。@ NiNiCkNaMe。 「連接表是否有附加數據」這個問題的答案是否定的。所以我需要爲出版商製作一張表格,然後以書籍形式出版商名單? – pouya