MybatisPlus集成SQLite3使用selectPage分页查询无法获取数据总数
MybatisPlus集成SQLite3分页无总条数问题解决方案
核心原因
MybatisPlus分页插件默认可能未正确识别SQLite数据库类型,导致生成的Count查询SQL与SQLite语法不兼容;或版本适配问题导致分页逻辑异常。
解决方案
1. 明确指定分页插件的数据库类型
在分页插件配置中,强制指定数据库为SQLite,避免自动识别错误:
@Configuration public class MybatisPlusConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); // 明确指定SQLite数据库类型 PaginationInnerInterceptor paginationInterceptor = new PaginationInnerInterceptor(DbType.SQLITE); // 开启溢出分页处理(可选,防止页码超出总页数时报错) paginationInterceptor.setOverflow(true); // 关闭Count查询优化(若默认优化导致SQL兼容问题) paginationInterceptor.setOptimizeCountSql(false); interceptor.addInnerInterceptor(paginationInterceptor); return interceptor; } }
2. 检查版本兼容性
- 确保MybatisPlus版本≥3.4.0(该版本后对SQLite的支持更完善)
- 引入正确的SQLite驱动依赖,示例Maven配置:
<dependency> <groupId>org.xerial</groupId> <artifactId>sqlite-jdbc</artifactId> <version>3.41.2.1</version> </dependency>
3. 排查生成的Count SQL语法
开启MybatisPlus的SQL日志,查看自动生成的Count语句是否符合SQLite语法:
# application.yml配置 mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
将控制台输出的Count SQL直接在SQLite客户端执行:
- 若SQL执行报错,检查是否存在表名/字段名与SQLite关键字冲突(如
order、user),需在实体类的@TableName或@TableField中添加转义符(如@TableName("\"order\"")) - 若SQL无结果,确认查询条件是否正确,是否存在数据过滤逻辑异常
4. 自定义Count查询(极端情况)
若自动生成的Count SQL始终无法适配,可在Mapper接口中自定义Count方法:
public interface YourMapper extends BaseMapper<YourEntity> { // 自定义Count查询 Long selectCustomCount(@Param("ew") Wrapper<YourEntity> queryWrapper); }
在XML中编写兼容SQLite的Count语句:
<select id="selectCustomCount" resultType="java.lang.Long"> SELECT COUNT(1) FROM your_table ${ew.customSqlSegment} </select>
分页时手动指定总条数:
IPage<YourEntity> page = new Page<>(pageNum, pageSize); // 手动设置总条数 page.setTotal(yourMapper.selectCustomCount(queryWrapper)); // 执行分页查询 page = yourMapper.selectPage(page, queryWrapper);
内容的提问来源于stack exchange,提问作者Troye Puth HelloDam
相关产品推荐
相关产品推荐

