一、Spring Boot整合JPA
(一)创建Spring Boot项目JPADemo




(二)创建ORM实体类
ORM: Object Relation Mapping 对象关系映射
1.创建评论实体类
在net.lbj.lesson07中创建子包bean,在子包中创建Comment
package net.lbj.lesson07.bean;
import javax.persistence.*;
/**
* 评论实体类
* 20210512
*/
@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 +
'}';
}
}
2.创建文章实体类

package net.lbj.lesson07.bean;
import javax.persistence.*;
import java.util.List;
/**
* 文章实体类
* 20210512
*/
@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;
}
@Override
public String toString() {
return "Article{" +
"id=" + id +
", title='" + title + '\'' +
", content='" + content + '\'' +
", commentList=" + commentList +
'}';
}
}
(三)创建自定义JpaRepository接口

package net.lbj.lesson07.repository;
import net.lbj.lesson07.bean.Article;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* 文章仓库接口
* 20210512
*/
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=dada
spring.datasource.druid.max-active=100
spring.datasource.druid.min-idle=10
spring.datasource.druid.initial-size=20

3.在测试类里编写测试方法

(1)注入文章仓库

(2)创建测试方法testFindAll()

运行查看结果

课堂练习:测试其他方法

-
测试findById()方法

-
测试save()方法
-
测试deleteById()方法
二、利用JPA实现个性化操作
(一)案例 : 根据文章编号分页查询评论
1.创建评论仓库接口

package net.lbj.lesson07.repository;
import net.lbj.lesson07.bean.Comment;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* 评论仓库接口
* 20210512
*/
public interface CommentRepository extends JpaRepository<Comment, Integer> {
}
2.按文章编号分页查询评论
package net.lbj.lesson07.repository;
import net.lbj.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 可分页对象,分页查询需要该参数
* @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);
}
3.创建测试类

添加测试注解,注入评论仓库

4.在测试类里创建测试方法
(1)创建测试方法testFindCommentPagedByArticleId01()
package net.lbj.lesson07;
import net.lbj.lesson07.bean.Comment;
import net.lbj.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;
/**
* 测试评论查询方法
* 20210512
*/
@SpringBootTest
public class CommentTests {
@Autowired //注入评论仓库
private CommentRepository commentRepository;
@Test //测试按文章编号分页查询评论,采用原生SQL语句
public void findCommentPagedByArticleId01() {
//当前页面索引
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 - 升序)

(2)创建测试方法testFindCommentPagedByArticleId02()

运行查看结果

本文介绍如何在SpringBoot项目中整合JPA,并通过具体案例演示如何进行实体类定义、仓库接口创建以及数据源配置。同时,还展示了如何利用JPA实现分页查询等个性化操作。

339

被折叠的 条评论
为什么被折叠?



