JPA關係對映系列五:many-to-many 關聯表存在額外欄位關係對映
SpringDataJPA是Spring Data的一個子專案,通過提供基於JPA的Repository極大的減少了JPA作為資料訪問方案的程式碼量,你僅僅需要編寫一個介面整合下SpringDataJPA內部定義的介面即可完成簡單的CRUD操作。
前言
本篇文章引導你通過Spring Boot
,Spring Data JPA
和MySQL
實現many-to-many
關聯表存在額外欄位下關係對映。
準備
- JDK 1.8 或更高版本
- Maven 3 或更高版本
- MySQL Server 5.6
技術棧
- Spring Data JPA
- Spring Boot
- MySQL
目錄結構
父pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.merryyou</groupId>
<artifactId>jpa-example</artifactId>
<version>1.0-SNAPSHOT</version>
<modules>
<module>one-to-one-foreignkey</module>
<module>one-to-one-primarykey</module>
<module>one-to-many</module>
<module>many-to-many</module>
<module>many-to-many-extra-columns</module>
</modules>
<packaging>pom</packaging>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.spring.platform</groupId>
<artifactId>platform-bom</artifactId>
<version>Brussels-SR6</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>
多對多關聯對映
目錄結構
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>jpa-example</artifactId>
<groupId>cn.merryyou</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>many-to-many-extra-columns</artifactId>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
多對多關聯
book.id
和 publisher.id
多對多關聯表book_publisher
還存在published_data
欄位
db.sql
CREATE DATABASE IF NOT EXISTS `jpa_manytomany_extracolumns` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `jpa_manytomany_extracolumns`;
--
-- Table structure for table `book`
--
DROP TABLE IF EXISTS `book`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `book` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `publisher`
--
DROP TABLE IF EXISTS `publisher`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `publisher` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8;
--
-- Table structure for table `book_publisher`
--
DROP TABLE IF EXISTS `book_publisher`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `book_publisher` (
`book_id` int(10) unsigned NOT NULL,
`publisher_id` int(10) unsigned NOT NULL,
`published_date` datetime DEFAULT NULL,
PRIMARY KEY (`book_id`,`publisher_id`),
KEY `fk_bookpublisher_publisher_idx` (`publisher_id`),
CONSTRAINT `fk_bookpublisher_book` FOREIGN KEY (`book_id`) REFERENCES `book` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_bookpublisher_publisher` FOREIGN KEY (`publisher_id`) REFERENCES `publisher` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
實體類
Book
@Entity
public class Book{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
@OneToMany(mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<BookPublisher> bookPublishers;
public Book() {
}
public Book(String name) {
this.name = name;
bookPublishers = new HashSet<>();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<BookPublisher> getBookPublishers() {
return bookPublishers;
}
public void setBookPublishers(Set<BookPublisher> bookPublishers) {
this.bookPublishers = bookPublishers;
}
}
Publisher
@Entity
public class Publisher {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
@OneToMany(mappedBy = "publisher")
private Set<BookPublisher> bookPublishers;
public Publisher(){
}
public Publisher(String name){
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<BookPublisher> getBookPublishers() {
return bookPublishers;
}
public void setBookPublishers(Set<BookPublisher> bookPublishers) {
this.bookPublishers = bookPublishers;
}
}
BookPublisher
@Entity
@Table(name = "book_publisher")
public class BookPublisher implements Serializable {
@Id
@ManyToOne
@JoinColumn(name = "book_id")
private Book book;
@Id
@ManyToOne
@JoinColumn(name = "publisher_id")
private Publisher publisher;
@Column(name = "published_date")
private Date publishedDate;
public Book getBook() {
return book;
}
public void setBook(Book book) {
this.book = book;
}
public Publisher getPublisher() {
return publisher;
}
public void setPublisher(Publisher publisher) {
this.publisher = publisher;
}
public Date getPublishedDate() {
return publishedDate;
}
public void setPublishedDate(Date publishedDate) {
this.publishedDate = publishedDate;
}
}
@Table
宣告此物件對映到資料庫的資料表,通過它可以為實體指定表(talbe),目錄(Catalog)和schema的名字。該註釋不是必須的,如果沒有則系統使用預設值(實體的短類名)。@Id
宣告此屬性為主鍵。該屬性值可以通過應該自身建立,但是Hibernate推薦通過Hibernate生成@GeneratedValue
指定主鍵的生成策略。- TABLE:使用表儲存id值
- IDENTITY:identitycolumn
- SEQUENCR :sequence
- AUTO:根據資料庫的不同使用上面三個
@Column
宣告該屬性與資料庫欄位的對映關係。@OneToMany
一對多關聯關係@ManyToMany
多對多關聯關係@JoinColumn
指定關聯的欄位@JoinTable
參考
Spring Data JPA Repository
BookRepository
public interface BookRepository extends JpaRepository<Book, Integer> {
}
PublisherRepository
public interface PublisherRepository extends JpaRepository<Publisher, Integer> {
}
Spring Data JPA
包含了一些內建的Repository
,實現了一些常用的方法:findone
,findall
,save
等。
application.yml
spring:
datasource:
url: jdbc:mysql://localhost/jpa_manytomany_extracolumns
username: root
password: admin
driver-class-name: com.mysql.jdbc.Driver
jpa:
show-sql: true
properties:
hibernate:
enable_lazy_load_no_trans: true
BookRepositoryTest
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class BookRepositoryTest {
@Autowired
private BookRepository bookRepository;
@Autowired
private PublisherRepository publisherRepository;
@Test
@Transactional
public void manyToManyExtraColumnsTest() throws Exception{
Book bookA = new Book("Book One");
Publisher publisherA = new Publisher("Publisher One");
BookPublisher bookPublisher = new BookPublisher();
bookPublisher.setBook(bookA);
bookPublisher.setPublisher(publisherA);
bookPublisher.setPublishedDate(new Date());
bookA.getBookPublishers().add(bookPublisher);
publisherRepository.save(publisherA);
bookRepository.save(bookA);
// test
System.out.println(bookA.getBookPublishers().size());
// update
bookA.getBookPublishers().remove(bookPublisher);
bookRepository.save(bookA);
// test
System.out.println(bookA.getBookPublishers().size());
}
}
程式碼下載
從我的 github 中下載,https://github.com/longfeizheng/jpa-example/tree/master/many-to-many-extra-columns
������關注微信小程式java架構師歷程
上下班的路上無聊嗎?還在看小說、新聞嗎?不知道怎樣提高自己的技術嗎?來吧這裡有你需要的java架構文章,1.5w+的java工程師都在看,你還在等什麼?
相關文章
- JPA關係對映系列四:many-to-many 關聯對映
- mybatis關聯關係對映MyBatis
- Hibernate 的關聯關係對映
- python 關係對映Python
- Spring Boot 入門系列(二十八) JPA 的實體對映關係,一對一,一對多,多對多關係對映!Spring Boot
- java物件關係對映ROMJava物件
- Spring Data JPA 之 一對一,一對多,多對多 關係對映Spring
- Hibernate (開源物件關係對映框架)物件框架
- MyBatis加強(1)~myBatis物件關係對映(多對一關係、一對多關係)、延遲/懶載入MyBatis物件
- Verilog程式碼和FPGA硬體的對映關係(五)FPGA
- JPA(3) 表關聯關係(多對一、一對多、多對多、一對一)
- C# 資料操作系列 - 6 EF Core 配置對映關係C#
- CRM和ERP的Sales Organization的對映關係
- 【新包】根據 appends 配置的關聯欄位對映關係,自動維護需要的 appends - Laravel Eloquent Append AutomationAPPLaravel
- Hibernate中實體類對映檔案表與表的關係模版
- TiDB從關係模型對映到key-value(圖)TiDB模型
- Mybatis實體關聯對映MyBatis
- ERP的Account group和CRM partner group的對映關係
- Verilog程式碼和FPGA硬體的對映關係(四)FPGA
- JPA中對映關係詳細說明(一對多,多對一,一對一、多對多)、@JoinColumn、mappedBy說明APP
- MyBatis實現一對一關聯對映MyBatis
- 表的關聯關係
- 體系結構、指令定址、對映關係、系統可靠性
- [新包] 根據 appends 配置的欄位對映關係,自動維護需要的 appends - Laravel Eloquent Append AutomationAPPLaravel
- Fluent API 配置實體和資料庫之間的對映關係API資料庫
- 淺談Mybatis中是如何實現這種多表關係的對映MyBatis
- day07-MyBatis的關聯對映01MyBatis
- JPA實體中欄位對映補充和嵌入物件物件
- JavaEE MyBatis關聯對映之多對多(教材學習筆記)JavaMyBatis筆記
- python 類關聯關係Python
- 上下文對映關係中如何解耦特定和通用的領域? - Nick Tune解耦
- windows域控裡,屬性和欄位對映表Windows
- Spring系列:Spring版本和JDK版本對應關係SpringJDK
- 設計模式存在哪些關聯關係,六種關係傻傻分不清--- UML圖示詳解設計模式
- HBase 的結構與表的對應關係
- Java資料型別與資料庫欄位型別對應關係Java資料型別資料庫
- 帶你徹底看懂React Native和Android原生控制元件之間的對映關係React NativeAndroid控制元件
- 在 CSDN 上面看到的一篇關於 Laravel 關聯表模型和多對多關係的文章Laravel模型