Java for Web学习笔记(一二九)映射(5)ManyToMany

ManyToMany需要中间表格。

小例子

一本书可以有N个作者,一个作者可以有N本书。

CREATE TABLE `Book` (
  `Id` bigint(20) unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY,
  `BookName` varchar(50) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB;

CREATE TABLE `Author` (
  `Id` bigint(20) unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY,
  `AuthorName` varchar(50) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB;

-- 通过Book_Author表格实现书和作者的关联
CREATE TABLE `Book_Author` (
  `Id` bigint(20) unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY,
  `Book_Id` bigint(20) unsigned NOT NULL,
  `Author_Id` bigint(20) unsigned NOT NULL,
  CONSTRAINT `BOOK_AUTHOR_BOOK_ID` FOREIGN KEY (`Book_Id`) REFERENCES `Book` (`Id`) ON DELETE CASCADE,
  CONSTRAINT `BOOK_AUTHOR_AUTHOR_ID` FOREIGN KEY (`Author_Id`) REFERENCES `Author` (`Id`) ON DELETE CASCADE
) ENGINE=InnoDB

Author的单向ManyToMany

@Entity
public class Author {
    private long id;
    private String authorName;
    private List<Book> books = new ArrayList<>();

    //【1】标记ManyToMany,里面的参数同之前学习
    @ManyToMany(fetch = FetchType.LAZY)
    //【2】标记关联表格Book_Author,@JoinTable也可以通过中间关联表格的OneToMany
    @JoinTable(name = "Book_Author",
               // 2.1)本Entity(Author)的主键关联表格Book_Author中的列Author_Id(外键)
               joinColumns = {@JoinColumn(name = "Author_Id")},
               // 2.2)对端Entity(Book)的列“Id”(缺省为主键)键关联表格Book_Author中的列Book_Id(外键)
               inverseJoinColumns = {@JoinColumn(name = "Book_Id",referencedColumnName = "Id")})
    public List<Book> getBooks() { ... }
    ......
}

Book和Author的双向ManyToMany

Author的代码同上,不再重复。

@Entity
public class Book {
    ... ...
    private List<Author> authors = new ArrayList<>();

    //标记ManyToMany,对方Entity(Author)的对应属性为books
    @ManyToMany(mappedBy = "books")
    public List<Author> getAuthors() { ... }
    ... ...
}

相关链接:我的Professional Java for Web Applications相关文章

©️2020 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值