1. 程式人生 > >JPA關係對映系列三:one-to-many和many-to-one

JPA關係對映系列三:one-to-many和many-to-one

SpringDataJPA是Spring Data的一個子專案,通過提供基於JPA的Repository極大的減少了JPA作為資料訪問方案的程式碼量,你僅僅需要編寫一個介面整合下SpringDataJPA內部定義的介面即可完成簡單的CRUD操作。

前言

本篇文章引導你通過Spring BootSpring Data JPAMySQL實現one-to-manymany-to-one關聯對映。

準備

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

技術棧

  • Spring Data JPA
  • Spring Boot
  • MySQL

目錄結構

https://raw.githubusercontent.com/longfeizheng/longfeizheng.github.io/master/images/jpa/Spring-data-jpa01.png

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

一對多和多對一

目錄結構

https://raw.githubusercontent.com/longfeizheng/longfeizheng.github.io/master/images/jpa/spring-data-jpa06.png

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>one-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>
一對多和多對一關聯

book.book-category_idbook_category.id
https://raw.githubusercontent.com/longfeizheng/longfeizheng.github.io/master/images/jpa/spring-data-jpa07.png

db.sql

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

--
-- Table structure for table `book_detail`
--

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

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

DROP TABLE IF EXISTS `book`;
CREATE TABLE `book` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`book_category_id` int(11) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_book_bookcategoryid_idx` (`book_category_id`),
CONSTRAINT `fk_book_bookcategoryid` FOREIGN KEY (`book_category_id`) REFERENCES `book_category` (`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;

    @ManyToOne
    @JoinColumn(name = "book_category_id")
    private BookCategory bookCategory;

    public Book() {

    }

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

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

    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 BookCategory getBookCategory() {
        return bookCategory;
    }

    public void setBookCategory(BookCategory bookCategory) {
        this.bookCategory = bookCategory;
    }
}
BookCategory
@Entity
@Table(name = "book_category")
public class BookCategory {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String name;

    @OneToMany(mappedBy = "bookCategory", cascade = CascadeType.ALL)
    private Set<Book> books;

    public BookCategory(){

    }

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

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

    @Override
    public String toString() {
        String result = String.format(
                "Category[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宣告此物件對映到資料庫的資料表,通過它可以為實體指定表(talbe),目錄(Catalog)和schema的名字。該註釋不是必須的,如果沒有則系統使用預設值(實體的短類名)。
  • @Id 宣告此屬性為主鍵。該屬性值可以通過應該自身建立,但是Hibernate推薦通過Hibernate生成
  • @GeneratedValue 指定主鍵的生成策略。

    1. TABLE:使用表儲存id值
    2. IDENTITY:identitycolumn
    3. SEQUENCR :sequence
    4. AUTO:根據資料庫的不同使用上面三個
  • @Column 宣告該屬性與資料庫欄位的對映關係。

  • @OneToMany 一對多關聯關係
  • @ManyToOne 多對一關聯關係
  • @JoinColumn 指定關聯的欄位
Spring Data JPA Repository
public interface BookCategoryRepository extends JpaRepository<BookCategory, Integer> {
}

Spring Data JPA包含了一些內建的Repository,實現了一些常用的方法:findonefindallsave等。

application.yml
spring:
  datasource:
    url: jdbc:mysql://localhost/jpa_onetomany
    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 BookCategoryRepositoryTest {

    @Autowired
    private BookCategoryRepository repository;


    @Test
    public void saveCategoryTest(){
        BookCategory categoryOne = new BookCategory("Category One");
        Set books = new HashSet<Book>(){{
            add(new Book("Book One", categoryOne));
            add(new Book("Book Two", categoryOne));
            add(new Book("Book Three", categoryOne));
        }};
        categoryOne.setBooks(books);

        BookCategory categoryTwo = new BookCategory("Category Two");
        Set bookBs = new HashSet<Book>(){{
            add(new Book("Book Four", categoryTwo));
            add(new Book("Book Five", categoryTwo));
            add(new Book("Book Six", categoryTwo));
        }};
        categoryTwo.setBooks(bookBs);

        Set allBooks = new HashSet();

        allBooks.add(categoryOne);
        allBooks.add(categoryTwo);

        List list = repository.save(allBooks);

        Assert.assertNotNull(list);
    }

    @Test
    public void findAll() throws Exception{

        for (BookCategory bookCategory : repository.findAll()) {
            log.info(bookCategory.toString());
        }
    }
}

程式碼下載

https://raw.githubusercontent.com/longfeizheng/longfeizheng.github.io/master/images/wechat/xiaochengxu.png

������關注微信小程式java架構師歷程
上下班的路上無聊嗎?還在看小說、新聞嗎?不知道怎樣提高自己的技術嗎?來吧這裡有你需要的java架構文章,1.5w+的java工程師都在看,你還在等什麼?