文章目录
- 零、学习目标
- 一、Spring Data JPA概述
- 1、Spring Data JPA简介
- 2、Spring Data JPA基本使用
- 3、使用Spring Data JPA进行数据操作的多种实现方式
- 4、自定义Repository接口中的@Transactional注解
- 5、变更操作,要配合使用@Query与@Modify注解
- 二、Spring Boot整合JPA
- (一)创建Spring Boot项目JPADemo
- (二)创建ORM实体类
- 1、创建评论实体类 - Comment
- 2、创建文章实体类 - Article
- (三)创建自定义JpaRepository接口 - ArticleRepository
- (四)添加数据源依赖,配置数据源属性
- 1、在pom.xml里添加阿里巴巴数据源依赖
- 2、在全局配置文件里配置数据源
- 3、在测试类里编写测试方法
- (1)注入文章仓库 - ArticleRepository
- (2)创建测试方法testFindAll()
- 课堂练习:测试其它方法
- 三、利用JPA实现个性化操作
- (一)案例 - 根据文章编号分页查询评论
- 1、创建评论仓库接口 - CommentRepository
- 2、定义按文章编号分页查询评论的方法
- 3、创建测试类 - CommentTests
- 4、在测试类里创建测试方法
- (1)创建测试方法testFindCommentPagedByArticleId01()
- (2)创建测试方法testFindCommentPagedByArticleId02()
- (二)案例 - 根据文章编号更新作者
- 1、在评论仓库接口里编写updateAuthorByArticleId()方法
- 2、在测试类CommentTests里创建测试方法testUpdateAuthorByArticleId()
- (三)案例 - 根据评论作者删除评论记录
- 1、在评论仓库接口里编写deleteCommentByAuthor()方法
- 2、在测试类CommentTests里创建测试方法testDeleteCommentByAuthor()
- 四、利用JPA默认方法实现个性化操作
- (一)案例 - 根据文章编号更新作者
- (二)案例 - 根据评论作者删除评论记录
零、学习目标
- 熟悉Spring Data JPA基本语法和使用
- 掌握Spring Boot与JPA的整合使用
一、Spring Data JPA概述
1、Spring Data JPA简介
- Spring Data JPA (JPA: Java Persistence API)是Spring基于ORM框架、JPA规范的基础上封装的一套JPA应用框架,它提供了增删改查等常用功能,使开发者可以用较少的代码实现数据操作,同时还易于扩展。
2、Spring Data JPA基本使用
- 编写ORM实体类:实体类与数据表进行映射,并且配置好映射关系。
- 编写Repository接口:针对不同的表数据操作编写各自对应的Repository接口,并根据需要编写对应的数据操作方法。
3、使用Spring Data JPA进行数据操作的多种实现方式
- 如果自定义接口继承了JpaRepository接口,则默认包含了一些常用的CRUD方法。
- 自定义Repository接口中,可以使用
@Query
注解配合SQL语句进行数据的查、改、删操作。 - 自定义Repository接口中,可以直接使用方法名关键字进行查询操作。
4、自定义Repository接口中的@Transactional注解
- 在自定义的Repository接口中,针对数据的变更操作(修改、删除),无论是否使用了
@Query
注解,都必须在方法上方添加@Transactional
注解进行事务管理,否则程序执行就会出现InvalidDataAccessApiUsageException
异常。 - 如果在调用Repository接口方法的业务层Service类上已经添加了
@Transactional
注解进行事务管理,那么Repository接口文件中就可以省略@Transactional
注解。
5、变更操作,要配合使用@Query与@Modify注解
- 在自定义的Repository接口中,使用
@Query
注解方式执行数据变更操作(修改、删除),除了要使用@Query
注解,还必须添加@Modifying
注解表示数据变更。
二、Spring Boot整合JPA
(一)创建Spring Boot项目JPADemo
- 设置项目元数据
- 添加项目依赖
- 设置项目名称与保存位置
- 完成项目初始化工作
(二)创建ORM实体类
- ORM: Object Relation Mapping 对象关系映射 (Object: Java Bean; Relation: Table)
1、创建评论实体类 - Comment
package net.hw.lesson07.bean;import javax.persistence.*;/*** 功能:评论实体类* 作者:华卫* 日期:2021年05月12日*/
@Entity(name = "t_comment")
public class Comment {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)@Column(name = "id")private Integer id;@Column(name = "content")private String content;@Column(name = "author")private String author;@Column(name = "a_id")private Integer aId;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getContent() {return content;}public void setContent(String content) {this.content = content;}public String getAuthor() {return author;}public void setAuthor(String author) {this.author = author;}public Integer getaId() {return aId;}public void setaId(Integer aId) {this.aId = aId;}@Overridepublic String toString() {return "Comment{" +"id=" + id +", content='" + content + '\'' +", author='" + author + '\'' +", aId=" + aId +'}';}
}
@Entity
中的name
对应数据库中表名GenerationType.IDENTITY
为MySQL中自增使用的策略,不同类型的数据库使用策略不同
2、创建文章实体类 - Article
package net.hw.lesson07.bean;import javax.persistence.*;
import java.util.List;/*** 功能:文章实体类* 作者:华卫* 日期:2021年05月12日*/
@Entity(name = "t_article")
public class Article {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)@Column(name = "id")private Integer id;@Column(name = "title")private String title;@Column(name = "content")private String content;// 查询时将子表一并查询出来@OneToMany(fetch = FetchType.EAGER) // FetchType.LAZY 懒加载@JoinTable(name = "t_comment", joinColumns = {@JoinColumn(name = "a_id")},inverseJoinColumns = {@JoinColumn(name = "id")})private List<Comment> commentList;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getContent() {return content;}public void setContent(String content) {this.content = content;}public List<Comment> getCommentList() {return commentList;}public void setCommentList(List<Comment> commentList) {this.commentList = commentList;}@Overridepublic String toString() {return "Article{" +"id=" + id +", title='" + title + '\'' +", content='" + content + '\'' +", commentList=" + commentList +'}';}
}
(三)创建自定义JpaRepository接口 - ArticleRepository
- 创建文章仓库接口ArticleRepository
package net.hw.lesson07.repository;import net.hw.lesson07.bean.Article;
import org.springframework.data.jpa.repository.JpaRepository;/*** 功能:文章仓库接口* 作者:华卫* 日期:2020年08月11日*/
public interface ArticleRepository extends JpaRepository<Article, Integer> {
}
- 注意,接口里什么代码也没写,是不是感觉很简单?
(四)添加数据源依赖,配置数据源属性
1、在pom.xml里添加阿里巴巴数据源依赖
<dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.2.6</version>
</dependency>
2、在全局配置文件里配置数据源
# 配置数据源
spring.datasource.url=jdbc:mysql://localhost:3306/blog?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=p@ssw0rd
spring.datasource.druid.max-active=100
spring.datasource.druid.min-idle=10
spring.datasource.druid.initial-size=20
3、在测试类里编写测试方法
- 点开项目测试类
(1)注入文章仓库 - ArticleRepository
(2)创建测试方法testFindAll()
- 运行测试方法,查看结果
课堂练习:测试其它方法
- 测试findById()方法
- 测试save()方法
- 测试deleteById()方法
三、利用JPA实现个性化操作
- 豆瓣图书的书评是分页显示,每页最多20条书评
(一)案例 - 根据文章编号分页查询评论
1、创建评论仓库接口 - CommentRepository
package net.hw.lesson07.repository;import net.hw.lesson07.bean.Comment;
import org.springframework.data.jpa.repository.JpaRepository;/*** 功能:评论仓库接口* 作者:华卫* 日期:2020年08月11日*/
public interface CommentRepository extends JpaRepository<Comment, Integer> {
}
2、定义按文章编号分页查询评论的方法
/** * 根据文章ID进行分页查询评论 * nativeQuery = true, 表示使用原生SQL语句,否则使用HQL语句 * @param aId 查询条件字段(文章编号) * @param pageable 可分页对象,分页查询需要该参数 * @return 返回page对象,包含page的相关信息及查询结果集 */
@Query(value = "select * from t_comment where a_id = ?1", nativeQuery = true)
Page<Comment> findCommentPagedByArticleId01(Integer aId, Pageable pageable); /** * 根据文章ID进行分页查询评论 * 没有设置nativeQuery,默认就是false,表示使用HQL语句 * @param aId 查询条件字段(文章编号) * @param pageable 可分页对象,分页查询需要该参数 * @return 返回page对象,包含page的相关信息及查询结果集 */
@Query(value = "select c from t_comment c where c.aId = ?1")
Page<Comment> findCommentPagedByArticleId02(Integer aId, Pageable pageable);
- 分页类:
Pageable
完整路径是org.springframework.data.domain.Pageable
,导包不要导错了 - 两种查询方式:原生sql查询和基于对象的查询,两种方式可以任意选择一种。注意,
@Query
注解不设置nativeQuery属性,默认就是基于对象的查询。 - 基于对象的查询:
@Query(value = "select c from t_comment c where c.aId = ?1")
,t_comment取个别名c,可以理解为表所对应的实体,select子句不能用*
,必须用c
,表明查询实体的所有属性,如果要查询实体的某些属性,那么可以这样写:@Query(value = "select c.id, c.author, c.content from t_comment c where c.aId = ?1")
;where子句不能用表的字段名a_id
,而应该用对应实体的属性aId
,但是要用实体c
作前缀,即c.aId
。占位符:?1
表示第一个占位符,当然第二个占位符就是?2
。
3、创建测试类 - CommentTests
- 添加测试注解,注入评论仓库
4、在测试类里创建测试方法
- 文章编号为1的评论有3条,下面我们将3条评论分两页显示,每页大小为2(最多两条记录)。第1页:id为1和3的两条评论;第2页:id为7的一条评论。
(1)创建测试方法testFindCommentPagedByArticleId01()
- 设置pageIndex = 0,表明当前页为第1页
- 设置pageSize = 2,表明每页最多两条记录
package net.hw.lesson07;import net.hw.lesson07.bean.Comment;
import net.hw.lesson07.repository.CommentRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;import java.util.List;/*** 功能:测试评论查询方法.* 作者:华卫* 日期:2021年05月12日*/
@SpringBootTest
public class CommentTests {@Autowired // 注入评论仓库private CommentRepository commentRepository;@Test // 测试按文章编号分页查询评论,采用原生SQL语句public void testFindCommentPagedByArticleId01() {// 当前页面索引int pageIndex = 0; // 当前页 - 第1页// 设置页面大小int pageSize = 2; // 每页最多2条记录// 创建分页器Pageable pageable = PageRequest.of(pageIndex, pageSize);// 查询文章编号为1的页面对象Page<Comment> page = commentRepository.findCommentPagedByArticleId01(1, pageable);// 获取页面对象里的评论列表List<Comment> comments = page.getContent();// 获取总页数int totalPages = page.getTotalPages();// 输出页面信息System.out.println("当前页:" + (pageIndex + 1));System.out.println("总页数:" + totalPages);// 输出当前页全部评论comments.forEach(comment -> System.out.println(comment));}
}
-
运行测试方法,查看结果
-
修改页索引值为1,显示第2页评论
-
假如希望每页评论按照评论编号降序排列,那么该如何操作呢?
-
Sort.Direction.DESC
- 降序;Sort.Direction.ASC
- 升序
-
运行测试方法,查看结果
-
当然也可以按照评论表其它字段来排序,比如按
content
或author
排序,大家不妨尝试一下,看看结果如何。
(2)创建测试方法testFindCommentPagedByArticleId02()
- 运行测试方法,查看结果
- 大家可以看到,运行结果跟
testFindCommentPagedByArticleId01()
测试方法最后一次运行结果是完全一样的。不论是原生sql查询还是基于对象的查询,最终分页查询的效果是相同的。
(二)案例 - 根据文章编号更新作者
1、在评论仓库接口里编写updateAuthorByArticleId()方法
2、在测试类CommentTests里创建测试方法testUpdateAuthorByArticleId()
- 运行测试方法,查看结果
- 在Navicat里打开评论表,查看文章编号为1的评论作者是不是都改成了“无心剑”
(三)案例 - 根据评论作者删除评论记录
1、在评论仓库接口里编写deleteCommentByAuthor()方法
2、在测试类CommentTests里创建测试方法testDeleteCommentByAuthor()
- 运行测试方法,查看结果
- 在Navicat里打开评论表,看看作者为“无心剑”的评论是否被删除了。
- 运行blog.sql脚本,恢复数据库blog的原始数据
四、利用JPA默认方法实现个性化操作
- 在生产实际中,绝大多数的功能都可用JPA提供的默认方法进行实现。
(一)案例 - 根据文章编号更新作者
-
在测试类CommentTests里创建测试方法testUpdateAuthorByArticleId02()
-
基本思路:查出所有文章编号为1的记录,然后修改作者为“无心剑”,再保存。
-
运行测试方法,查看结果
-
在Navicat里打开评论表,看看文章编号为1的评论作者是否都改成了“无心剑”
(二)案例 - 根据评论作者删除评论记录
- 在测试类CommentTests里创建测试方法testDeleteCommentByAuthor02()
-
- 基本思路:查出评论作者为“无心剑”的记录,然后逐个删除。
- 基本思路:查出评论作者为“无心剑”的记录,然后逐个删除。
- 运行测试方法,查看结果
- 在Navicat里打开评论表,看看作者为“无心剑”的评论是否被删除了。
- 运行blog.sql脚本,恢复数据库blog的原始数据