JPA关系映射之one-to-one、one-to-many、many-to-one和many-to-many

SpringDataJPA是Spring Data的一个子项目,通过提供基于JPA的Repository极大的减少了JPA作为数据访问方案的代码量,你仅仅需要编写一个接口集成下SpringDataJPA内部定义的接口即可完成简单的CRUD操作。

前言

本篇文章引导你通过Spring BootSpring Data JPAMySQL 映射一对一外键、一对一主键、一对多,多对一,多对多、多对多额外的列的关系。

准备

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

技术栈

  • Spring Data JPA
  • Spring Boot
  • MySQL

目录结构

JPA关系映射之one-to-one、one-to-many、many-to-one和many-to-many_第1张图片
https://raw.githubusercontent.com/longfeizheng/longfeizheng.github.io/master/images/jpa/Spring-data-jpa01.png

父pom.xml



    4.0.0

    cn.merryyou
    jpa-example
    1.0-SNAPSHOT
    
        one-to-one-foreignkey
        one-to-one-primarykey
        one-to-many
        many-to-many
        many-to-many-extra-columns
    
    pom


    
        
            
                io.spring.platform
                platform-bom
                Brussels-SR6
                pom
                import
            
        
    

一对一外键

目录结构

JPA关系映射之one-to-one、one-to-many、many-to-one和many-to-many_第2张图片
https://raw.githubusercontent.com/longfeizheng/longfeizheng.github.io/master/images/jpa/spring-data-jpa02.png

pom.xml


    
        jpa-example
        cn.merryyou
        1.0-SNAPSHOT
    
    4.0.0

    one-to-one-foreignkey

    
        UTF-8
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter-data-jpa
        

        
            mysql
            mysql-connector-java
            runtime
        

        
            org.projectlombok
            lombok
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
            
                org.apache.maven.plugins
                maven-compiler-plugin
                3.6.1
                
                    1.8
                    1.8
                
            
        
    

一对一关系

book.book_detail_idbook_detail.id

JPA关系映射之one-to-one、one-to-many、many-to-one和many-to-many_第3张图片
https://raw.githubusercontent.com/longfeizheng/longfeizheng.github.io/master/images/jpa/spring-data-jpa03.png

db.sql

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

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

DROP TABLE IF EXISTS `book_detail`;
CREATE TABLE `book_detail` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`number_of_pages` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 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_detail_id` int(11) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_book_bookdetail` (`book_detail_id`),
CONSTRAINT `fk_book_bookdetail` FOREIGN KEY (`book_detail_id`) REFERENCES `book_detail` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
实体类
Book
@Entity
@Data
@Table(name = "book")
public class Book {

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

    @Column(name = "name")
    private String name;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "book_detail_id")
//    @Lazy(false)
    private BookDetail bookDetail;

    public Book() {
    }

    public Book(String name, BookDetail bookDetail) {
        this.name = name;
        this.bookDetail = bookDetail;
    }
}
BookDetail
@Entity
@Table(name = "book_detail")
@Data
public class BookDetail {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Integer id;

    @Column(name = "number_of_pages")
    private Integer numberOfPages;

    @OneToOne(mappedBy = "bookDetail")
    private Book book;

    public BookDetail() {
    }

    public BookDetail(Integer numberOfPages) {
        this.numberOfPages = numberOfPages;
    }
}

  • @Table声明此对象映射到数据库的数据表,通过它可以为实体指定表(talbe),目录(Catalog)和schema的名字。该注释不是必须的,如果没有则系统使用默认值(实体的短类名)。

  • @Id 声明此属性为主键。该属性值可以通过应该自身创建,但是Hibernate推荐通过Hibernate生成

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

    1. TABLE:使用表保存id值
    2. IDENTITY:identitycolumn
    3. SEQUENCR :sequence
    4. AUTO:根据数据库的不同使用上面三个
  • @Column 声明该属性与数据库字段的映射关系。

  • @OneToOne 一对一关联关系

  • @JoinColumn 指定关联的字段

Spring Data JPA Repository
public interface BookRepository extends JpaRepository {
}

Spring Data JPA包含了一些内置的Repository,实现了一些常用的方法:findonefindallsave等。

application.yml
spring:
  datasource:
    url: jdbc:mysql://localhost/jpa_onetoone_foreignkey
    username: root
    password: admin
    driver-class-name: com.mysql.jdbc.Driver
  jpa:
    show-sql: true
BookRepositoryTest
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class BookRepositoryTest {

    @Autowired
    private BookRepository bookRepository;

    @Test
    public void saveTest() throws Exception {

        List books = new ArrayList<>();
        books.add(new Book("Book one", new BookDetail(1)));
        books.add(new Book("Book two", new BookDetail(2)));
        books.add(new Book("Book three", new BookDetail(3)));
        List bookList = bookRepository.save(books);
        Assert.assertNotNull(bookList);
        Assert.assertEquals(3, bookList.size());
    }

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

}

其它

剩下的一对一主键、一对多,多对一,多对多、多对多额外的列参考如上。

代码下载

从我的 github 中下载,https://github.com/longfeizheng/jpa-example

你可能感兴趣的:(JPA关系映射之one-to-one、one-to-many、many-to-one和many-to-many)