欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot+JPA分页

程序员文章站 2022-04-30 13:52:58
...

SpringBoot+JPA分页

1.前期准备

1.新建springboot项目
SpringBoot+JPA分页
2.在pom文件中导入依赖

		 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
            <version>2.2.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-web</artifactId>
            <version>1.2.3</version>
        </dependency>

3.准备实体类 Student

/**
 *实体类
 */
@Entity
@Table(name = "t_blog")
public class Student {
  @Id //主键
  @GeneratedValue //自增长
  private long studentNo;
  private String loginPwd;
  private String studentName;
  private String sex;
  private long gradeId;
  private String phone;
  private String address;
  private java.sql.Timestamp bornDate;
  private String email;
  private String identityCard;

  public Student(String loginPwd, String studentName, String sex, long gradeId, String phone, String address, Timestamp bornDate, String email, String identityCard) {
    this.loginPwd = loginPwd;
    this.studentName = studentName;
    this.sex = sex;
    this.gradeId = gradeId;
    this.phone = phone;
    this.address = address;
    this.bornDate = bornDate;
    this.email = email;
    this.identityCard = identityCard;
  }

  public Student() {
  }

  public long getStudentNo() {
    return studentNo;
  }

  public void setStudentNo(long studentNo) {
    this.studentNo = studentNo;
  }


  public String getLoginPwd() {
    return loginPwd;
  }

  public void setLoginPwd(String loginPwd) {
    this.loginPwd = loginPwd;
  }


  public String getStudentName() {
    return studentName;
  }

  public void setStudentName(String studentName) {
    this.studentName = studentName;
  }


  public String getSex() {
    return sex;
  }

  public void setSex(String sex) {
    this.sex = sex;
  }


  public long getGradeId() {
    return gradeId;
  }

  public void setGradeId(long gradeId) {
    this.gradeId = gradeId;
  }


  public String getPhone() {
    return phone;
  }

  public void setPhone(String phone) {
    this.phone = phone;
  }


  public String getAddress() {
    return address;
  }

  public void setAddress(String address) {
    this.address = address;
  }


  public java.sql.Timestamp getBornDate() {
    return bornDate;
  }

  public void setBornDate(java.sql.Timestamp bornDate) {
    this.bornDate = bornDate;
  }


  public String getEmail() {
    return email;
  }

  public void setEmail(String email) {
    this.email = email;
  }


  public String getIdentityCard() {
    return identityCard;
  }

  public void setIdentityCard(String identityCard) {
    this.identityCard = identityCard;
  }

}

4.application-dev.yml文件

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/MyStudent?zeroDateTimeBehavior=CONVERT_TO_NULL&serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8
    username: root
    password: root
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
  thymeleaf:
    mode: HTML

5.新建数据库
SpringBoot+JPA分页
6.启动项目生成表
SpringBoot+JPA分页
7.执行sql语句,添加数据

INSERT INTO `s_student` VALUES (10001, '天津市河西区', '2019-11-15 09:50:05.000000', 'aaa@qq.com', 1, '43100319960505098', 'pwd123', '13645667783', '男', '郭靖');
INSERT INTO `s_student` VALUES (10002, '地址不详', '2019-11-15 09:50:05.000000', 'aaa@qq.com', 1, '43100319960505098', 'pwd123', '13645667783', '男', '李斯文');
INSERT INTO `s_student` VALUES (10003, '河南洛阳', '2019-11-15 09:50:05.000000', 'aaa@qq.com', 1, '43100319960505098', 'pwd123', '13645667783', '男', '李文才');
INSERT INTO `s_student` VALUES (10004, '北京市海淀区', '2019-11-15 09:50:05.000000', 'aaa@qq.com', 1, '43100319960505098', 'pwd123', '13645667783', '男', '张萍');
INSERT INTO `s_student` VALUES (10005, '北京市东城区', '2019-11-15 09:50:05.000000', 'aaa@qq.com', 1, '43100319960505098', 'pwd123', '13645667783', '男', '宋小宝');
INSERT INTO `s_student` VALUES (10006, '天津市河西区', '2019-11-15 09:50:05.000000', 'aaa@qq.com', 1, '43100319960505098', 'pwd123', '13645667783', '男', '靖');
INSERT INTO `s_student` VALUES (10007, '地址不详', '2019-11-15 09:50:05.000000', 'aaa@qq.com', 1, '43100319960505098', 'pwd123', '13645667783', '男', '文');
INSERT INTO `s_student` VALUES (10008, '河南洛阳', '2019-11-15 09:50:05.000000', 'aaa@qq.com', 1, '43100319960505098', 'pwd123', '13645667783', '男', '李才');
INSERT INTO `s_student` VALUES (10009, '北京市海淀区', '2019-11-15 09:50:05.000000', 'aaa@qq.com', 1, '43100319960505098', 'pwd123', '13645667783', '男', '萍');
INSERT INTO `s_student` VALUES (10010, '北京市东城区', '2019-11-15 09:50:05.000000', 'aaa@qq.com', 1, '43100319960505098', 'pwd123', '13645667783', '男', '小宝');

二 创建 dao层

继承JpaRepository<entity,type> ,entity代表实体类,type代表实体类的数据类型

import com.demo.springboot_jpa.pojo.Student;
import org.springframework.data.jpa.repository.JpaRepository;

public interface StudentRepository extends JpaRepository<Student,Long> {

}

三 创建Service以及ServiceImpl层

StudentService 接口的方法里面将Page作为返回类型,Pageable 作为参数.

StudentService

import com.demo.springboot_jpa.pojo.Student;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

/**
 * @author Moon
 */
public interface StudentService {
    /**
     * 分页获得集合
     * @param pageable
     * @return
     */
    Page<Student> listStudents(Pageable pageable);
}

StudentServiceImpl 实现 StudentService 接口,使用@Autowired注解导入StudentRepository,然后调用它的有参方法findAll(pageable)

StudentServiceImpl

import com.demo.springboot_jpa.dao.StudentRepository;
import com.demo.springboot_jpa.pojo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

/**
 * @author Moon
 */
@Service
public class StudentServiceImpl  implements StudentService {
    @Autowired
    StudentRepository studentRepository;
    @Override
    public Page<Student> listStudents(Pageable pageable) {
        return studentRepository.findAll(pageable);
    }
}

四 创建Controller控制层

import com.demo.springboot_jpa.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author Moon
 */
@Controller
public class StudentController {
    @Autowired
    StudentService studentService;
    @RequestMapping("/students")
    public String students(@PageableDefault(size = 3,sort = {"studentNo"},direction = Sort.Direction.ASC) Pageable pageable,
                           Model model){
        model.addAttribute("page",studentService.listStudents(pageable));
        System.out.println("studentList:"+studentService.listStudents(pageable));
        return "student/studentList";
    }
}

五 编写前端页面

前端页面一定要放在resource里面的templates文件夹里面(没有的话创建一个),这里我们在templates文件夹里面创了一个admin文件夹
SpringBoot+JPA分页
在springboot中我们提供了thymeleaf模板,使用th标签将后台的东西在html网页中展示出来;
例如: th:each=“student,iterStat : ${page.content}”
student表示每次循环展示的对象
iterStat用来实现计数的功能配合 KaTeX parse error: Expected '}', got 'EOF' at end of input: …/students(page={page.number}-1)}实则就是再次调用Controller层的方法并且把page页码值传过去
th:unless="${page.first} 如果不是第一页才显示标签里面的内容,用来判断

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>学生列表</title>
</head>
<body>
    <table>
        <tr>
            <th>计数</th>
            <th>学号</th>
            <th>姓名</th>
            <th>性别</th>
            <th>年级</th>
            <th>电话</th>
            <th>地址</th>
        </tr>
        <tr th:each="student,iterStat : ${page.content}">
            <td th:text="${iterStat.count}">1</td>
            <td th:text="${student.studentNo}">1</td>
            <td th:text="${student.studentName}">刻意练习清单</td>
            <td th:text="${student.sex}">认知升级</td>
            <td th:text="${student.gradeId}"></td>
            <td th:text="${student.phone}">草稿</td>
            <td th:text="${student.address}">2017-10-02 09:45</td>
        </tr>
    </table>
        <br>
    <a th:href="@{/students(page=${page.number}-1)}" class="  item" th:unless="${page.first}">上一页</a>
    <a th:href="@{/students(page=${page.number}+1)}" class=" item" th:unless="${page.last}">下一页</a>
    </body>
</html>

六 测试

浏览器输入 http://localhost:8080/students
SpringBoot+JPA分页

相关标签: JPA