一、Spring Data JPA概述
1、Spring Data JPA简介
Spring Data JPA是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
1、创建Spring Boot项目JPADemo
添加项目依赖
2、创建ORM实体类
ORM: Object Relation Mapping 对象关系映射
(1)、创建评论实体类Comment
package net.wz.lesson07.bean;
import javax.persistence.*;
@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;
}
@Override
public String toString() {
return "Comment{" +
"id=" + id +
", content='" + content + '\'' +
", author='" + author + '\'' +
", aId=" + aId +
'}';
}
}
@Entity中的name对应数据库中表名
GenerationType.IDENTITY为MySQL中的自增使用的策略,不同类型的数据库使用策略不同
(2)、创建文章实体类Article
package net.wz.lesson07.bean;
import javax.persistence.*;
import java.util.List;
@Entity(name = "t_article")
public class Article {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
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;
}
@Override
public String toString() {
return "Article{" +
"id=" + id +
", title='" + title + '\'' +
", content='" + content + '\'' +
", commentList=" + commentList +
'}';
}
}
3、创建自定义JpaRepository接口 - ArticleRepository
创建文章仓库接口ArticleRepository
package net.wz.lesson07.repository;
import net.wz.lesson07.bean.Article;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ArticleRepository extends JpaRepository<Article, Integer> {
}
注意,接口里什么代码也没写,是不是感觉很简单?
4、添加数据源依赖,配置数据源属性
(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=123456
spring.datasource.druid.max-active=100
spring.datasource.druid.min-idle=10
spring.datasource.druid.initial-size=20
(3)、在测试类里编写测试方法
(1)注入文章仓库
(2)创建测试方法testFindAll()
运行测试方法,查看结果
三、利用JPA实现个性化操作
(一)案例 - 根据文章编号分页查询评论
1、创建评论仓库接口CommentRepository
package net.wz.lesson07.repository;
import net.wz.lesson07.bean.Comment;
import org.springframework.data.jpa.repository.JpaRepository;
CommentRepository extends JpaRepository<Comment, Integer> {
}
2、定义按文章编号分页查询评论的方法
package net.wz.lesson07.repository;
import net.wz.lesson07.bean.Comment;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
public interface CommentRepository extends JpaRepository<Comment, Integer> {
/**
* 据文章ID进行分页查询评论
* nativeQuery = true表示原生sql语句,否则使用的是实体对象
* @param aId 查询条件字段
* @param pageable 凡是要实现分页的查询,只需传递pageable参数即可
* @return 返回page对象,包含page的相关信息及查询结果集
*/
@Query(value = "select * from t_comment where a_id = ?1", nativeQuery = true)
Page<Comment> findCommentPagedByArticleId01(Integer aId, Pageable pageable);
@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.wz.lesson07;
import net.wz.lesson07.bean.Comment;
import net.wz.lesson07.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.junit.jupiter.api.Test;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import java.util.List;
@SpringBootTest
public class CommentTests {
// 注入评论仓库
@Autowired
private CommentRepository commentRepository;
@Test
public void testFindCommentPagedByArticleId01() {
// 当前页面索引
int pageIndex = 0;
// 设置页面大小
int pageSize = 2;
// 创建分页器
Pageable pageable = PageRequest.of(pageIndex, pageSize);
// 查询文章编号为1的页面对象
Page<Comment> page = commentRepository.findCommentPagedByArticleId01(1, pageable);
// 获取页面对象里的评论列表
List<Comment> comments = page.getContent();
// 获取页索引
int number = page.getNumber();
// 获取总页数
int totalPages = page.getTotalPages();
System.out.println("当前页:" + (number + 1)); // 页索引加1才是页码
System.out.println("总页数:" + totalPages);
// 输出当前页全部评论
for (Comment comment : comments) {
System.out.println(comment);
}
}
}
运行测试方法,查看结果