springboot集成mybatis自定义分页

mybatis实现分页有很多种方式

借助数组进行分页

原理:进行数据库查询操作时,获取到数据库中所有满足条件的记录,保存在应用的临时数组中,再通过List的subList方法,获取到满足条件的所有记录。

借助Sql语句进行分页

实现:通过sql语句实现分页也是非常简单的,只是需要改变我们查询的语句就能实现了,即在sql语句后面添加limit分页语句。

拦截器分页

自定义拦截器实现了拦截所有以ByPage结尾的查询语句,并且利用获取到的分页相关参数统一在sql语句后面加上limit分页的相关语句,一劳永逸。

RowBounds实现分页

原理:通过RowBounds实现分页和通过数组方式分页原理差不多,都是一次获取所有符合条件的数据,然后在内存中对大数据进行操作,实现分页效果。只是数组分页需要我们自己去实现分页逻辑,这里更加简化而已。

第三方分页插件

如常用的mybatis-plus、pagehelper。

今天要讲的是mybatis自定义分页

mybatis自定义分页

首先还是在StudentMapper接口中添加sql语句查询的方法,如下:

/**
* 自定义分页查询
* @param data
* @return
*/
List queryStudentsBySql(Map data);

然后在StudentMapper.xml文件中编写sql语句通过limiy关键字进行分页:

接下来还是在StudentService中对sql分页实现。

public List queryStudentsBySql(int currPage, int pageSize) {
Map data = new HashMap();
data.put("currIndex", (currPage-1)*pageSize);
data.put("pageSize", pageSize);
return studentMapper.queryStudentsBySql(data);
}

controller中调用service方法

@GetMapping("getByPage/{currPage}/{pageSize}")
public List getByPage(@PathVariable int currPage,@PathVariable int pageSize) {
return studentService.queryStudentsBySql(currPage,pageSize);
}

sql分页语句如下:select * from table limit index, pageSize;

所以在service中计算出currIndex:要开始查询的第一条记录的索引。

全部代码如下:

mysql

CREATE TABLE `t_student` (
  `id` int NOT NULL AUTO_INCREMENT,
  `city_no` varchar(30) DEFAULT NULL,
  `city_name` varchar(30) DEFAULT NULL,
  `city_type` varchar(30) DEFAULT NULL,
  `p_city_no` varchar(30) DEFAULT NULL,
  `stu_no` varchar(30) DEFAULT NULL,
  `stu_name` varchar(30) DEFAULT NULL,
  `stu_grade_no` varchar(30) DEFAULT NULL,
  `stu_grade_name` varchar(30) DEFAULT NULL,
  `stu_class_no` varchar(30) DEFAULT NULL,
  `stu_class_name` varchar(30) DEFAULT NULL,
  `exam_time` varchar(30) DEFAULT NULL,
  `course` varchar(255) DEFAULT NULL,
  `score` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

代码架构

pom.xml

<?xml version="1.0" encoding="UTF-8"?>

   4.0.0
   
      org.springframework.boot
      spring-boot-starter-parent
      2.6.4
       
   
   com.fish
   mybatis
   0.0.1-SNAPSHOT
   mybatis
   Spring Boot集成mybatis
   
      1.8
   
   
      
         org.mybatis.spring.boot
         mybatis-spring-boot-starter
         2.2.2
      

      
         org.springframework.boot
         spring-boot-starter-test
         test
      

      
      
         mysql
         mysql-connector-java
      

      
         org.projectlombok
         lombok
         1.18.20
      
      
         org.springframework.boot
         spring-boot-starter-web
         RELEASE
         compile
      
   

   
      
         
            org.springframework.boot
            spring-boot-maven-plugin
         
      
   

application.yml

spring:
  profiles:
    active: dev

application-dev.yml

server:
  port: 8080
spring:
  datasource:
    username: username
    password: password
    url: jdbc:mysql://192.168.80.128:3301/test_db?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
    driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
  # 配置mapper的扫描,找到所有的mapper.xml映射文件
  # 搜索指定包别名
  typeAliasesPackage: com.fish.**.mapper
  mapperLocations: classpath*:mapper/*Mapper.xml

Student.java实体类

package com.fish.mybatis.entity;

import lombok.Data;

/**
 * @author fish
 */
@Data
public class Student {
    private Integer id;
    private String cityNo;
    private String cityName;
    private String cityType;
    private String pCityNo;
    private String stuNo;
    private String stuName;
    private String stuGradeNo;
    private String stuGradeName;
    private String stuClassNo;
    private String stuClassName;
    private String examTime;
    private String course;
    private Integer score;
}

StudentMapper.java

package com.fish.mybatis.mapper;

import com.fish.mybatis.entity.Student;
import com.fish.mybatis.entity.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

/**
 * @author fish
 */
@Repository
public interface StudentMapper {
    /**
     * 根据主键查询
     * @param id
     * @return
     */
    Student getById(int id);

    /**
     * 根据全部学生
     * @return
     */
    List getByAll();

    /**
     * 自定义分页查询
     * @param data
     * @return
     */
    List queryStudentsBySql(Map data);
}

StudentMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>


    
        
        
        
        
        
        
        
        
        
        
        
        
        
        
    
    
    
    

StudentService.java

package com.fish.mybatis.service;

import com.fish.mybatis.entity.Student;
import com.fish.mybatis.mapper.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author fish
 */
@Service
public class StudentService {
    @Autowired
    StudentMapper studentMapper;

    public Student getById(int id) {
        return studentMapper.getById(id);
    }
    public List getByAll() {
        List studentList=studentMapper.getByAll();
        return studentList;
    }
    public List queryStudentsBySql(int currPage, int pageSize) {
        Map data = new HashMap();
        data.put("currIndex", (currPage-1)*pageSize);
        data.put("pageSize", pageSize);
        return studentMapper.queryStudentsBySql(data);
    }
}

StudentController.java

package com.fish.mybatis.controller;

import com.fish.mybatis.entity.Student;
import com.fish.mybatis.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author fish
 */
@RestController
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentService studentService;

    @RequestMapping("getById/{id}")
    public Student getById(@PathVariable int id) {
        return studentService.getById(id);
    }
    @RequestMapping("getByAll")
    public List getByAll() {
        return studentService.getByAll();
    }

    @GetMapping("getByPage/{currPage}/{pageSize}")
    public List getByPage(@PathVariable int currPage,@PathVariable int pageSize) {
        return studentService.queryStudentsBySql(currPage,pageSize);
    }
}

MybatisApplication.java

package com.fish.mybatis;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author fish
 */
@MapperScan("com.fish.mybatis.mapper")
@SpringBootApplication
public class MybatisApplication {

   public static void main(String[] args) {
      SpringApplication.run(MybatisApplication.class, args);
   }

}

测试:

在浏览器输入http://localhost:8080/student/getByPage/3/3获取第一页的数据,每页显示两条数据。

结果:

从输出结果可以看出和数组分页的结果是一致的,因此sql语句的分页也是没问题的。

在实际工作中有些很复杂的SQL使用第三方分页插件不靠谱还是需要自己实现分页的。

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章