当前位置: 首页 > article >正文

基于Spring Boot和MyBatis的后端主键分页查询接口示例

基于Spring Boot和MyBatis的后端主键分页查询接口示例

    • 1. 项目结构
    • 2. 代码实现
      • (1)实体类 `User.java`
      • (2)Mapper接口 `UserMapper.java`
      • (3)Mapper XML文件 `UserMapper.xml`
      • (4)Service层 `UserService.java`
      • (5)Controller层 `UserController.java`
      • (6)Spring Boot启动类 `DemoApplication.java`
      • (7)配置文件 `application.yml`
    • 3. 接口使用示例
      • 请求示例
      • 响应示例
    • 4. 总结


下面是一个基于Spring Boot和MyBatis的后端分页查询接口示例,使用基于主键的分页查询优化方法。假设我们有一个用户表user,其中包含自增主键id和其他字段(如nameemail等)。

1. 项目结构

src
├── main
│   ├── java
│   │   └── com
│   │       └── example
│   │           ├── controller
│   │           │   └── UserController.java
│   │           ├── entity
│   │           │   └── User.java
│   │           ├── mapper
│   │           │   └── UserMapper.java
│   │           ├── service
│   │           │   └── UserService.java
│   │           └── DemoApplication.java
│   └── resources
│       ├── application.yml
│       └── mapper
│           └── UserMapper.xml
└── test
    └── java

2. 代码实现

(1)实体类 User.java

package com.example.entity;

public class User {
    private Long id;
    private String name;
    private String email;

    // Getters and Setters
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

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

(2)Mapper接口 UserMapper.java

package com.example.mapper;

import com.example.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

import java.util.List;

@Mapper
public interface UserMapper {
    // 基于主键的分页查询
    List<User> findUsersAfterId(@Param("lastId") Long lastId, @Param("size") int size);
}

(3)Mapper XML文件 UserMapper.xml

resources/mapper目录下创建UserMapper.xml文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.example.mapper.UserMapper">
    <select id="findUsersAfterId" resultType="com.example.entity.User">
        SELECT id, name, email
        FROM user
        WHERE id > #{lastId}
        ORDER BY id
        LIMIT #{size}
    </select>
</mapper>

(4)Service层 UserService.java

package com.example.service;

import com.example.entity.User;
import com.example.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    // 基于主键的分页查询
    public List<User> getUsersAfterId(Long lastId, int size) {
        return userMapper.findUsersAfterId(lastId, size);
    }
}

(5)Controller层 UserController.java

package com.example.controller;

import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    // 分页查询接口
    @GetMapping("/users")
    public List<User> getUsers(@RequestParam(value = "lastId", defaultValue = "0") Long lastId,
                               @RequestParam(value = "size", defaultValue = "10") int size) {
        return userService.getUsersAfterId(lastId, size);
    }
}

(6)Spring Boot启动类 DemoApplication.java

package com.example;

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

@SpringBootApplication
@MapperScan("com.example.mapper") // 扫描Mapper接口
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

(7)配置文件 application.yml

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/your_database?useSSL=false&serverTimezone=UTC
    username: your_username
    password: your_password
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis:
  mapper-locations: classpath:mapper/*.xml

3. 接口使用示例

请求示例

  • 第一页:
    GET /users?lastId=0&size=10
    
  • 第二页(假设第一页的最后一条记录的id为10):
    GET /users?lastId=10&size=10
    

响应示例

[
    {
        "id": 1,
        "name": "Alice",
        "email": "alice@example.com"
    },
    {
        "id": 2,
        "name": "Bob",
        "email": "bob@example.com"
    },
    ...
]

4. 总结

通过基于主键的分页查询优化方法,我们可以显著提升千万数据量下的分页查询性能。这种方法的核心思想是:

  1. 利用自增主键的有序性,避免扫描大量数据。
  2. 每次查询时记录最后一条记录的id,作为下一次查询的起始点。

本文提供了一个完整的Spring Boot + MyBatis实现案例,涵盖了从实体类、Mapper接口、Service层到Controller层的完整代码。希望这个案例能够帮助你更好地理解和应用分页查询优化技术。


参考资料

  • Spring Boot官方文档:https://spring.io/projects/spring-boot
  • MyBatis官方文档:https://mybatis.org/mybatis-3/zh/index.html
  • MySQL分页查询优化实战经验分享

http://www.kler.cn/a/543535.html

相关文章:

  • 【论文阅读】Revisiting the Assumption of Latent Separability for Backdoor Defenses
  • 使用 SDKMAN! 在 Mac(包括 ARM 架构的 M1/M2 芯片)安装适配 Java 8 的 Maven
  • π 的奥秘:如何用有理数逼近无理数?
  • 【STM32】通过HAL库Flash建立FatFS文件系统并配置为USB虚拟U盘MSC
  • 探索技术新边界:让 HTML 电子凭证与二维码、PDF 完美融合
  • 基于Java的分布式系统架构设计与实现
  • DeepSeek-R1-技术文档
  • 基于 MATLAB 的粒子滤波算法实现示例,用于处理手机传感器数据并估计电梯运行参数。
  • github - 使用
  • Android和DLT日志系统
  • 云原生时代的开发利器
  • Spring Boot过滤器链:从入门到精通
  • AWTK fscript 中的 TCP/UDP 客户端扩展函数
  • 使用Python爬虫获取淘宝item_search_tmall API接口数据
  • 压缩stl文件大小
  • Go语言开发桌面应用基础框架(wails v3)-开箱即用框架
  • 【系统架构设计师】嵌入式系统之JTAG接口
  • VSCode选择编译工具(CMake)
  • visual studio 在kylin v10上跨平台编译时c++标准库提示缺少无法打开的问题解决
  • pyside6 的QThread多个案例
  • vue开发06:前端通过webpack配置处理跨域问题
  • 大模型知识蒸馏:技术突破与应用范式重构——从DeepSeek创新看AI基础设施演进路径
  • PHP:从入门到进阶的全面指南
  • Day88:加载游戏图片
  • 2. grafana插件安装并接入zabbix
  • 酷柚易汛ERP 3.0 【2025-02-12】系统升级日志