背景
我们在使用Mybatis分页查询数据列表时,在用户的一个请求中常常需要同时返回当前页的列表数据以及满足条件的数据总条数。以下介绍了三种常见方案。具体使用哪种,具体场景具体分析。
实现方案
1)执行两次SQL,一次查列表,一次查总数
这种方法最简单,也最容易实现。缺点是需要执行两次SQL查询。
2)分页插件PageHelper
另一种常用的方式就是使用Mybatis提供的PageHelper插件。实际上PageHelper插件的原理同1)一样,就是执行两次SQL查询。
3)通过select ... found_rows()命令,可以只执行一次SQL查询。但这个功能要求connectionUrl参数包含allowMultiQueries=true,且对于如zebra等集成工具,就算配了allowMultiQueries=true,也不一定起作用。因而需要根据实际场景测试,再决定使用哪种方案。
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.domain.Order">
<select id="queryListAppendTotal"
parameterType="com.domain.OrderExample"
resultMap="BaseResultMap, recordCounts">
select
SQL_CALC_FOUND_ROWS
<include refid="Base_Column_List"/>
from order_example
<if test="_parameter != null">
<include refid="Example_Where_Clause"/>
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
<if test="limit != null">
<if test="offSet != null">