JPA關(guān)系映射系列四:many-to-many 關(guān)聯(lián)映射

SpringDataJPA是Spring Data的一個(gè)子項(xiàng)目荤懂,通過提供基于JPA的Repository極大的減少了JPA作為數(shù)據(jù)訪問方案的代碼量,你僅僅需要編寫一個(gè)接口集成下SpringDataJPA內(nèi)部定義的接口即可完成簡單的CRUD操作硫眨。

前言

本篇文章引導(dǎo)你通過Spring BootSpring Data JPAMySQL實(shí)現(xiàn)many-to-many關(guān)聯(lián)映射撩笆。

準(zhǔn)備

  • JDK 1.8 或更高版本
  • Maven 3 或更高版本
  • MySQL Server 5.6

技術(shù)棧

  • Spring Data JPA
  • Spring Boot
  • MySQL

目錄結(jié)構(gòu)

[圖片上傳失敗...(image-6352f3-1520077140162)]

父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>

多對多關(guān)聯(lián)映射

目錄結(jié)構(gòu)

[圖片上傳失敗...(image-e4badc-1520077140162)]

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</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>
多對多關(guān)聯(lián)

book.idpublisher.id 多對多關(guān)聯(lián)表book_publisher

db.sql

CREATE DATABASE  IF NOT EXISTS `jpa_manytomany`;
USE `jpa_manytomany`;

--
-- Table structure for table `book`
--

DROP TABLE IF EXISTS `book`;
CREATE TABLE `book` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8;

--
-- Table structure for table `publisher`
--

DROP TABLE IF EXISTS `publisher`;
CREATE TABLE `publisher` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8;
--
-- Table structure for table `book_publisher`
--

DROP TABLE IF EXISTS `book_publisher`;
CREATE TABLE `book_publisher` (
`book_id` int(10) unsigned NOT NULL,
`publisher_id` int(10) unsigned NOT 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;


實(shí)體類
Book
@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String name;
    @ManyToMany(cascade = CascadeType.MERGE)
    @JoinTable(name = "book_publisher", joinColumns = @JoinColumn(name = "book_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "publisher_id", referencedColumnName = "id"))
    private Set<Publisher> publishers = new HashSet<>();

    public Book() {

    }

    public Book(String name) {
        this.name = name;
    }

    public Book(String name, Set<Publisher> publishers) {
        this.name = name;
        this.publishers = publishers;
    }

    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<Publisher> getPublishers() {
        return publishers;
    }

    public void setPublishers(Set<Publisher> publishers) {
        this.publishers = publishers;
    }

    @Override
    public String toString() {
        String result = String.format(
                "Book [id=%d, name='%s']%n",
                id, name);
        if (publishers != null) {
            for (Publisher publisher : publishers) {
                result += String.format(
                        "Publisher[id=%d, name='%s']%n",
                        publisher.getId(), publisher.getName());
            }
        }

        return result;
    }
}

Publisher
@Entity
public class Publisher {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String name;
    @ManyToMany(mappedBy = "publishers")
    private Set<Book> books = new HashSet<>();

    public Publisher(){

    }

    public Publisher(String name){
        this.name = name;
    }

    public Publisher(String name, Set<Book> books){
        this.name = name;
        this.books = books;
    }

    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<Book> getBooks() {
        return books;
    }

    public void setBooks(Set<Book> books) {
        this.books = books;
    }

    @Override
    public String toString() {
        String result = String.format(
                "Publisher [id=%d, name='%s']%n",
                id, name);
        if (books != null) {
            for(Book book : books) {
                result += String.format(
                        "Book[id=%d, name='%s']%n",
                        book.getId(), book.getName());
            }
        }

        return result;
    }
}

  • @Table聲明此對象映射到數(shù)據(jù)庫的數(shù)據(jù)表捺球,通過它可以為實(shí)體指定表(talbe),目錄(Catalog)和schema的名字缸浦。該注釋不是必須的夕冲,如果沒有則系統(tǒng)使用默認(rèn)值(實(shí)體的短類名)。

  • @Id 聲明此屬性為主鍵裂逐。該屬性值可以通過應(yīng)該自身創(chuàng)建歹鱼,但是Hibernate推薦通過Hibernate生成

  • @GeneratedValue 指定主鍵的生成策略。

    1. TABLE:使用表保存id值
    2. IDENTITY:identitycolumn
    3. SEQUENCR :sequence
    4. AUTO:根據(jù)數(shù)據(jù)庫的不同使用上面三個(gè)
  • @Column 聲明該屬性與數(shù)據(jù)庫字段的映射關(guān)系卜高。

  • @ManyToMany 多對多關(guān)聯(lián)關(guān)系

  • @JoinColumn 指定關(guān)聯(lián)的字段

  • @JoinTable 參考

Spring Data JPA Repository
BookRepository
public interface BookRepository extends JpaRepository<Book, Integer> {
}
PublisherRepository
public interface PublisherRepository extends JpaRepository<Publisher, Integer> {
}

Spring Data JPA包含了一些內(nèi)置的Repository弥姻,實(shí)現(xiàn)了一些常用的方法:findonefindall掺涛,save等庭敦。

application.yml
spring:
  datasource:
    url: jdbc:mysql://localhost/jpa_manytomany
    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
    public void saveTest() throws Exception {

        Publisher publisherA = new Publisher("Publisher One");
        Publisher publisherB = new Publisher("Publisher Two");

        Book bookA = new Book("Book One");
        bookA.setPublishers(new HashSet<Publisher>() {{
            add(publisherA);
            add(publisherB);
        }});

        bookRepository.save(bookA);

    }

    @Test
    public void saveTest1() throws Exception{
        Publisher publisher = publisherRepository.findOne(24);
        Book bookA = new Book("Book Two");
        bookA.getPublishers().add(publisher);
        bookRepository.save(bookA);
    }

    @Test
    public void saveTest2() throws Exception{
        Book two = bookRepository.findOne(18);
        Publisher publisher = publisherRepository.findOne(25);
        two.getPublishers().add(publisher);
        bookRepository.save(two);
    }

    @Test
    public void findPublisherTest() throws Exception{
        Publisher publisher = publisherRepository.findOne(24);
        Set<Book> books = publisher.getBooks();
        for(Book book: books){
            log.info(book.getName()+"..."+book.getId());
        }
        Assert.assertNotNull(publisher);
        Assert.assertNotNull(publisher.getName());
    }

    @Test
    public void findAllTest() throws Exception {
        for (Book book : bookRepository.findAll()) {
            log.info(book.toString());
        }
    }

    @Test
    public void findBookTest() throws Exception{
        Book book = bookRepository.findOne(16);
        Set<Publisher> publishers = book.getPublishers();
        for(Publisher publisher: publishers){
            log.info(publisher.getName()+"..."+publisher.getId());
        }
        Assert.assertNotNull(book);
        Assert.assertNotNull(book.getName());
    }
}

代碼下載

從我的 github 中下載,https://github.com/longfeizheng/jpa-example/tree/master/many-to-many


??????關(guān)注微信小程序java架構(gòu)師歷程
上下班的路上無聊嗎薪缆?還在看小說秧廉、新聞嗎?不知道怎樣提高自己的技術(shù)嗎拣帽?來吧這里有你需要的java架構(gòu)文章疼电,1.5w+的java工程師都在看,你還在等什么减拭?

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末蔽豺,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子拧粪,更是在濱河造成了極大的恐慌修陡,老刑警劉巖沧侥,帶你破解...
    沈念sama閱讀 212,884評論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異濒析,居然都是意外死亡正什,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,755評論 3 385
  • 文/潘曉璐 我一進(jìn)店門号杏,熙熙樓的掌柜王于貴愁眉苦臉地迎上來婴氮,“玉大人,你說我怎么就攤上這事盾致≈骶” “怎么了?”我有些...
    開封第一講書人閱讀 158,369評論 0 348
  • 文/不壞的土叔 我叫張陵庭惜,是天一觀的道長罩驻。 經(jīng)常有香客問我,道長护赊,這世上最難降的妖魔是什么惠遏? 我笑而不...
    開封第一講書人閱讀 56,799評論 1 285
  • 正文 為了忘掉前任,我火速辦了婚禮骏啰,結(jié)果婚禮上节吮,老公的妹妹穿的比我還像新娘。我一直安慰自己判耕,他們只是感情好透绩,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,910評論 6 386
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著壁熄,像睡著了一般帚豪。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上草丧,一...
    開封第一講書人閱讀 50,096評論 1 291
  • 那天狸臣,我揣著相機(jī)與錄音,去河邊找鬼昌执。 笑死烛亦,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的仙蚜。 我是一名探鬼主播此洲,決...
    沈念sama閱讀 39,159評論 3 411
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼委粉!你這毒婦竟也來了呜师?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,917評論 0 268
  • 序言:老撾萬榮一對情侶失蹤贾节,失蹤者是張志新(化名)和其女友劉穎汁汗,沒想到半個(gè)月后衷畦,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,360評論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡知牌,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,673評論 2 327
  • 正文 我和宋清朗相戀三年祈争,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片角寸。...
    茶點(diǎn)故事閱讀 38,814評論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡菩混,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出扁藕,到底是詐尸還是另有隱情沮峡,我是刑警寧澤,帶...
    沈念sama閱讀 34,509評論 4 334
  • 正文 年R本政府宣布亿柑,位于F島的核電站邢疙,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏望薄。R本人自食惡果不足惜疟游,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,156評論 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望痕支。 院中可真熱鬧颁虐,春花似錦、人聲如沸采转。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,882評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽故慈。三九已至,卻和暖如春框全,著一層夾襖步出監(jiān)牢的瞬間察绷,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,123評論 1 267
  • 我被黑心中介騙來泰國打工津辩, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留拆撼,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 46,641評論 2 362
  • 正文 我出身青樓喘沿,卻偏偏與公主長得像闸度,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子蚜印,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,728評論 2 351

推薦閱讀更多精彩內(nèi)容