Spring Boot JPA中关联表的使用

本文中,我们会将会通过一个Book和Category的关联关系,来讲解如何在JPA中使用。

添加依赖

我们还是使用H2内存数据库来做测试:

        <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency> <dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>

构建Entity

下面我们构建两个Entity:

@Data
@Entity
public class Book { @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title; @ManyToOne
private Category category;
}
@Data
@Entity
public class Category { @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name; @OneToMany(mappedBy = "category", cascade = CascadeType.ALL)
private List<Book> books;
}

上面我们定义了两个Entity,Category和Book是一对多的关系。我们通过@ManyToOne和@OneToMany来定义相应的关系。

构建Repository

我们接下来构建相应的Repository:

public interface BookRepository extends CrudRepository<Book, Long> {
long deleteByTitle(String title); @Modifying
@Query("delete from Book b where b.title=:title")
void deleteBooks(@Param("title") String title);
}
public interface CategoryRepository extends CrudRepository<Category, Long> {}

构建初始数据

为了方便测试,我们先构建需要的数据schema.sql和data.sql:

CREATE TABLE book (
id BIGINT NOT NULL AUTO_INCREMENT,
title VARCHAR(128) NOT NULL,
category_id BIGINT,
PRIMARY KEY (id)
); CREATE TABLE category (
id BIGINT NOT NULL AUTO_INCREMENT,
name VARCHAR(128) NOT NULL,
PRIMARY KEY (id)
);
insert into book(id,title,category_id)
values(1,'The Hobbit',1);
insert into book(id,title,category_id)
values(2,'The Rabbit',1); insert into category(id,name)
values(1,'category');

测试

我们看一下怎么从Book中删除一条数据:

    @Test
public void whenDeleteByIdFromRepository_thenDeletingShouldBeSuccessful() {
assertThat(bookRepository.count()).isEqualTo(2);
bookRepository.deleteById(1L);
assertThat(bookRepository.count()).isEqualTo(1);
}

再看一下category的删除:

    @Test
public void whenDeletingCategories_thenBooksShouldAlsoBeDeleted() {
categoryRepository.deleteAll();
assertThat(bookRepository.count()).isEqualTo(0);
assertThat(categoryRepository.count()).isEqualTo(0);
}

再看一下book的删除:

    @Test
public void whenDeletingBooks_thenCategoriesShouldAlsoBeDeleted() {
bookRepository.deleteAll();
assertThat(bookRepository.count()).isEqualTo(0);
assertThat(categoryRepository.count()).isEqualTo(1);
}

因为我们只在Category中指定了cascade = CascadeType.ALL, 所以删除category的时候可以删除相关联的Book,但是删除Book的时候不会删除相关联的category。

本文的例子可以参考https://github.com/ddean2009/learn-springboot2/tree/master/springboot-jpa-relation

更多教程请参考 flydean的博客

Spring Boot JPA中关联表的使用的更多相关文章

  1. spring boot JPA中实体类常用注解

    spring boot jpa中的注解很多,参数也比较多.没必要全部记住,但是经常查看官方文档也比较麻烦,记录一下一些常用的注解.通过一些具体的例子来帮助记忆. @Entity @Table(name ...

  2. Spring Boot JPA 中transaction的使用

    文章目录 @Transactional的实现 @Transactional的使用 Transaction的传播级别 REQUIRED SUPPORTS MANDATORY NEVER NOT_SUPP ...

  3. Spring Boot JPA中使用@Entity和@Table

    文章目录 默认实现 使用@Table自定义表格名字 在JPQL Queries中重写表格名字 Spring Boot JPA中使用@Entity和@Table 本文中我们会讲解如何在Spring Bo ...

  4. Spring Boot JPA中java 8 的应用

    文章目录 Optional Stream API CompletableFuture Spring Boot JPA中java 8 的应用 上篇文章中我们讲到了如何在Spring Boot中使用JPA ...

  5. spring boot jpa 使用update 报错解决办法

    在spring boot jpa 中自定义sql,执行update操作报错解决办法: 在@Query(...)上添加 @Modifying@Transactional注解

  6. Spring Boot JPA的查询语句

    文章目录 准备工作 Containing, Contains, IsContaining 和 Like StartsWith EndsWith 大小写不敏感 Not @Query Spring Boo ...

  7. Spring Boot + JPA(hibernate 5) 开发时,数据库表名大小写问题

      (转载)Spring Boot + JPA(hibernate 5) 开发时,数据库表名大小写问题   这几天在用spring boot开发项目, 在开发的过程中遇到一个问题hibernate在执 ...

  8. Spring Boot Jpa 表名小写转大写

    今天在使用SpringBoot整合Hibernate后创建表,表名为小写,而在linux下,mysql的表名是区分大小写的,因此在我的数据表中,就出现了两个一样的表 act_id_user 和  AC ...

  9. Spring Boot(五):Spring Boot Jpa 的使用

    在上篇文章Spring Boot(二):Web 综合开发中简单介绍了一下 Spring Boot Jpa 的基础性使用,这篇文章将更加全面的介绍 Spring Boot Jpa 常见用法以及注意事项. ...

随机推荐

  1. C 苟富贵

    时间限制 : 15000 MS   空间限制 : 524288 KB 问题描述 你最近买六合彩赚了很多钱,导致一个银行账户存不下了,于是你开设了 N 个账户,第 i 个账户里存有 Ai 元. 你的好友 ...

  2. div实现富文本编辑框

    ocument.execCommand()方法处理Html数据时常用语法格式如下:document.execCommand(sCommand[,交互方式, 动态参数]) 其中:sCommand为指令参 ...

  3. on duplicate key update 的用法说明(解决批量操作数据,有就更新,没有就新增)mybatis批量操作数据更新和添加

    项目用的ORM框架是用springdatajpa来做的,有些批量数据操作的话,用这个效率太低,所以用mybatis自己写sql优化一下. 一般情况,我们肯定是先查询,有就修改,没有就添加,这样的话,单 ...

  4. Shell基础应用

                                                                  Shell基础应用 案例1:Shell基础应用 案例2:简单Shell脚本的 ...

  5. 基础类封装-Requests库封装

    #!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2020/03/18 23:37 # @Author : Tang Yiwei # @ ...

  6. Python 1基础语法一(注释、行与缩进、多行语句、空行和代码组)

    一.注释Python中单行注释以 # 开头,实例如下: # 第一个注释 print ("Hello, Python!") # 第二个注释 输出结果为: ============== ...

  7. Git应用详解第五讲:远程仓库Github与Git图形化界面

    前言 前情提要:Git应用详解第四讲:版本回退的三种方式与stash 这一节将会介绍本地仓库与远程仓库的一些简单互动以及几款常用的Git图形化界面,让你更加方便地使用git. 一.Git裸库 简单来说 ...

  8. NumPy学习2:创建数组

    1.使用array创建数组 b = array([2, 3, 4])print bprint b.dtype 2.把序列转化为数组 b = array( [ (1.5,2,3), (4,5,6) ] ...

  9. spark模型运行时无法连接摸个excutors异常org.apache.spark.shuffle.FetchFailedException: Failed to connect to xxxx/xx.xx.xx.xx:xxxx

    error:org.apache.spark.shuffle.FetchFailedException: Failed to connect to xxxx/xx.xx.xx.xx:xxxx 定位来定 ...

  10. SpringMVC框架详细教程(六)_HelloWorld

    HelloWorld 在src下创建包com.pudding.controller,然后创建一个类HelloWorldController: package com.pudding.controlle ...