跳到主要内容MyBatisPlus 与 Thymeleaf 全栈分页实战 | 极客日志Java大前端java
MyBatisPlus 与 Thymeleaf 全栈分页实战
分页是 Web 应用的核心功能,直接影响数据加载效率与用户体验。本方案基于 Spring Boot 集成 MyBatisPlus 实现后端分页查询,配合 Thymeleaf 模板引擎完成前端渲染。通过配置分页插件、编写实体类与服务层逻辑,结合 Ajax 动态加载表格与分页条,可快速构建稳定可靠的分页模块。文中还涵盖了常见配置缺失导致分页失效的排查方法,适合 Java 全栈开发参考。
修罗1 浏览 前言
分页是 Web 应用的核心功能,直接影响数据加载效率与用户体验。本方案基于 Spring Boot 集成 MyBatisPlus 实现后端分页查询,配合 Thymeleaf 模板引擎完成前端渲染。通过配置分页插件、编写实体类与服务层逻辑,结合 Ajax 动态加载表格与分页条,可快速构建稳定可靠的分页模块。文中还涵盖了常见配置缺失导致分页失效的排查方法,适合 Java 全栈开发参考。
环境搭建及表结构
依赖引入
在 Maven 项目的 pom.xml 中,我们需要引入 MyBatisPlus 启动器、Lombok 以及 PostgreSQL 驱动。这里以 PostgreSQL 为例,若使用 MySQL 需调整驱动依赖。
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>net.postgis</groupId>
<artifactId>postgis-jdbc</artifactId>
<>2.5.0
version
</version>
</dependency>
示例表结构
我们以城市停水信息数据为例,重点展示数据的分页展示逻辑。基础表结构包含主键、区域、时间等字段,具体设计如下:
Java 后台分页实现
实体类定义
实体类直接映射数据库表,利用 Lombok 简化 Getter/Setter 生成。注意注解中的字段映射关系,确保驼峰命名与下划线列名正确对应。
package org.yelang.pcwater.domain;
import java.io.Serializable;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.google.gson.annotations.SerializedName;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@TableName(value = "biz_stop_water_info")
@NoArgsConstructor
@AllArgsConstructor
@Setter
@Getter
@ToString
public class StopWaterInfo implements Serializable {
private static final long serialVersionUID = -1582687729349525826L;
@TableId(value="pk_id")
private Long pkId;
@TableField(value = "affect_user")
private String affectUser;
@TableField(value = "affected_range")
private String affectedRange;
@TableField(value = "affect_region")
private String affectRegion;
@TableField(value = "created_on")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createdOn;
@TableField(value = "inform_emergency_plan")
private String informEmergencyPlan;
@TableField(value = "inform_id")
private Integer informId;
@TableField(value = "inform_remark")
private String informRemark;
@TableField(value = "main_lead_path")
private String mainLeadPath;
private String position;
private String reason;
@TableField(value = "service_phone")
private String servicePhone;
@TableField(value = "show_end_date")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@SerializedName("showenddate")
private Date showEndDate;
@TableField(value = "stop_end_time")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date stopEndTime;
@TableField(value = "stop_start_time")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date stopStartTime;
@TableField(value = "stop_time")
@SerializedName("stoptime")
private String stopTime;
@TableField(value = "stopwater_type")
private String stopwaterType;
@TableField(value = "supply_emergency_plan")
private String supplyEmergencyPlan;
@TableField(value = "supply_remark")
private String supplyRemark;
private String title;
private String type;
@TableField(value = "regin_name")
private String reginName;
@TableField(value = "sync_sno")
private Long syncSno;
}
业务层分页逻辑
分页的核心在于 IPage 对象的使用。我们在 Service 接口定义分页方法,并在实现类中构造 QueryWrapper 和 Page 对象。
IPage<StopWaterInfo> page(Integer pageNum, Integer pageSize, String regionName);
@Override
public IPage<StopWaterInfo> page(Integer pageNum, Integer pageSize, String regionName) {
QueryWrapper<StopWaterInfo> queryWrapper = new QueryWrapper<>();
queryWrapper.like("regin_name", regionName);
queryWrapper.orderByDesc("created_on");
Page<StopWaterInfo> page = new Page<>(pageNum, pageSize);
return this.baseMapper.selectPage(page, queryWrapper);
}
这里通过构造 Page 对象,将控制层传入的当前页码和每页大小一起传入,配合 QueryWrapper 进行条件过滤和排序,最后调用 selectPage 完成查询。
控制层 API
Controller 接收前端参数,调用 Service 后返回封装好的结果。注意参数默认值的设置,避免空指针异常。
@PostMapping("/list")
@ResponseBody
public AjaxResult list(@RequestParam(defaultValue = "1") Integer pageNum,
@RequestParam(defaultValue = "5") Integer pageSize,
@RequestParam(defaultValue = "") String regionName) {
IPage<StopWaterInfo> page = waterInfoService.page(pageNum, pageSize, regionName);
AjaxResult result = AjaxResult.success();
result.put("data", page);
return result;
}
Thymeleaf 分页集成
Thymeleaf 作为现代 Java 模板引擎,能很好地与 Spring Boot 集成。虽然本例主要演示 Ajax 动态渲染,但理解其表达式绑定对后续静态页面开发很有帮助。
分页表格展示
HTML 结构中预留表格主体,利用 JavaScript 从后端获取数据并动态填充。
<div>
<table>
<thead>
<tr>
<th>创建时间</th>
<th>停水地点</th>
<th>原因</th>
</tr>
</thead>
<tbody id="table-body">
</tbody>
</table>
</div>
JavaScript 负责发起 Ajax 请求并渲染表格:
function renderTablePage(page) {
currentPage = page;
const tableBody = document.getElementById('table-body');
tableBody.innerHTML = '';
$.ajax({
type: "post",
url: ctx + "datasync/list",
dataType: "json",
cache: false,
processData: true,
data: {"pageNum": page, "pageSize": EVENTS_PER_PAGE, "regionName": ""},
success: function(result) {
const pageData = result.data.records;
const totalPages = result.data.pages;
if (pageData.length === 0) {
tableBody.innerHTML = `<tr><td colspan="5">未找到符合条件的停水事件。</td></tr>`;
} else {
pageData.forEach(event => {
const row = tableBody.insertRow();
row.innerHTML = `
<td>${event.createdOn}</td>
<td>${event.position}</td>
<td>${event.reason}</td>
`;
});
}
renderPagination(totalPages);
},
error: function() {
tableBody.innerHTML = `<tr><td colspan="5">未找到符合条件的停水事件。</td></tr>`;
}
});
}
拿到响应后,遍历 records 动态拼接行,同时触发分页条渲染。
分页条集成
分页条通常位于表格下方,提供上一页、下一页跳转功能。
<div>
<nav aria-label="Table Pagination">
<ul id="table-pagination"></ul>
</nav>
</div>
function renderPagination(totalPages) {
const paginationContainer = document.getElementById('table-pagination');
paginationContainer.innerHTML = '';
if (totalPages <= 1) return;
paginationContainer.innerHTML += `
<li ${currentPage === 1 ? 'disabled' : ''}>
<a href="#" onclick="changePage(${totalPages},${currentPage - 1})" aria-label="Previous">前一页</a>
</li>
`;
paginationContainer.innerHTML += `
<li ${currentPage === totalPages ? 'disabled' : ''}>
<a href="#" onclick="changePage(${totalPages},${currentPage + 1})" aria-label="Next">后一页</a>
</li>
`;
}
注意修复了原代码中 <li> 标签属性语法错误,确保禁用状态能正确显示。
可能遇到的问题
分页不展示
如果在页面上看到数据全部加载且无分页条,通常是后端分页插件未生效。此时 IPage 对象中的 pages 字段可能为 1,导致前端认为只有一页。
解决方案
检查是否配置了 MybatisPlusInterceptor 并添加了 PaginationInnerInterceptor。这是 MyBatisPlus 拦截 SQL 执行的关键组件。
package org.yelang.pcwater.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor i = new MybatisPlusInterceptor();
i.addInnerInterceptor(new PaginationInnerInterceptor(DbType.POSTGRE_SQL));
return i;
}
}
总结
本文演示了从后端实体定义、Service 分页逻辑到前端 Ajax 渲染的全流程。核心在于 MyBatisPlus 的 IPage 对象与前端 JS 的无缝对接。只要分页插件配置正确,基本就能解决大部分分页失效问题。这套方案适用于大多数传统 Web 项目场景,开发者可根据实际业务需求扩展更多交互细节。
相关免费在线工具
- Keycode 信息
查找任何按下的键的javascript键代码、代码、位置和修饰符。 在线工具,Keycode 信息在线工具,online
- Escape 与 Native 编解码
JavaScript 字符串转义/反转义;Java 风格 \uXXXX(Native2Ascii)编码与解码。 在线工具,Escape 与 Native 编解码在线工具,online
- JavaScript / HTML 格式化
使用 Prettier 在浏览器内格式化 JavaScript 或 HTML 片段。 在线工具,JavaScript / HTML 格式化在线工具,online
- JavaScript 压缩与混淆
Terser 压缩、变量名混淆,或 javascript-obfuscator 高强度混淆(体积会增大)。 在线工具,JavaScript 压缩与混淆在线工具,online
- Base64 字符串编码/解码
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
- Base64 文件转换器
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online