一对多映射有两种,一种是单向的,另一种的多向。我们一般是使用双向的,所以我就写写一对多的双向映射。
还是想昨天一样举个例子来说明:作者《===》作品,还是对数据进行增删改查。
我们一般是把外键建立在多方的,一个作者对应多个作品。
这个前一篇的差不多。我就主要写写有差异的地方吧!
还是要建立数据库表,
1 create table t_author( 2 id bigint primary key auto_increment, 3 authorName varchar(20) 4 ); 5 6 create table t_book( 7 id bigint primary key auto_increment, 8 bookName varchar(20), 9 fk_author_id int 10 );
实体:
Author.java
1 package com.cy.beans; 2 3 import java.io.Serializable; 4 import java.util.HashSet; 5 import java.util.Set; 6 7 public class Author implements Serializable { 8 private static final long serialVersionUID = 1L; 9 10 private long id; 11 private String authorName; 12 private Set<Book> books=new HashSet<Book>(); 13 14 public Author(){ 15 16 } 17 18 public long getId() { 19 return id; 20 } 21 22 public void setId(long id) { 23 this.id = id; 24 } 25 26 public String getAuthorName() { 27 return authorName; 28 } 29 30 public void setAuthorName(String authorName) { 31 this.authorName = authorName; 32 } 33 34 35 public Set<Book> getBooks() { 36 return books; 37 } 38 39 public void setBooks(Set<Book> books) { 40 this.books = books; 41 } 42 43 @Override 44 public String toString() { 45 return "Author [ + authorName + 46 ", books=" + books + "]"; 47 } 48 49 50 51 52 }