MyBatis 的分頁功能是基于內(nèi)存的分頁,即先查詢出所有記錄,再按起始位置和頁面容量取出結(jié)果。
本節(jié)我們?yōu)椴樵兙W(wǎng)站記錄增加分頁功能,要求結(jié)果列表按照 id 升序排列(本節(jié)示例基于《第一個MyBatis程序》一節(jié)的代碼實(shí)現(xiàn))。
WebsiteMapper 中方法如下。
/**
*
* @param site
* @param currentPageNo 起始位置
* @param pageSize 頁面容量
* @return
*/
public List<Website> selectWebsite(
@Param("site") Website site,
@Param("from") Integer currentPageNo,
@Param("pageSize") Integer pageSize);
相比原來的 selectWebsite 方法,增加了兩個參數(shù),起始位置(from)和頁面容量(pageSize),用于實(shí)現(xiàn)分頁查詢。
修改 WebsiteMapper.xml 的查詢語句,增加 limit 關(guān)鍵字,SQL 映射代碼如下。
<select id="selectWebsite" resultType="net.biancheng.po.Website">
SELECT id,name,url,age,country
FROM website
<trim prefix="where" prefixOverrides="and">
<if test="site.name != null and site.name !=''">
AND name LIKE CONCAT ('%',#{site.name},'%')
</if>
<if test="site.url!= null and site.url !=''">
AND url LIKE CONCAT ('%',#{site.url},'%')
</if>
ORDER BY id limit #{from},#{pageSize}
</trim>
</select>
WebsiteMapper 類中方法如下。
public List<Website> selectWebsite(Website website);
測試代碼如下。
public static void main(String[] args) throws IOException {
// 讀取配置文件mybatis-config.xml
InputStream config = Resources.getResourceAsStream("mybatis-config.xml");
// 根據(jù)配置文件構(gòu)建
SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(config);
// 通過SqlSessionFactory創(chuàng)建SqlSession
SqlSession ss = ssf.openSession();
Website site = new Website();
// site.setname("編程");
site.setUrl("http");
Integer pageSize = 3;
Integer currentPageNo = 0;
List<Website> siteList = new ArrayList<Website>();
siteList = ss.getMapper(WebsiteMapper.class).selectWebsite(site, currentPageNo, pageSize);
for (Website ws : siteList) {
System.out.println(ws);
}
}
輸出結(jié)果如下。
DEBUG [main] - ==> Preparing: SELECT id,name,url,age,country FROM website where url like concat ('%',?,'%') ORDER BY id limit ?,?
DEBUG [main] - ==> Parameters: http(String), 0(Integer), 3(Integer)
DEBUG [main] - <== Total: 3
Website[id=1,name=編程幫,url=http://www.jixiangtaizi.com.cn/,age=10,country=CN]
Website[id=2,name=C語言中文網(wǎng),url=https://c.cainiaoplus.com/,age=12,country=CN]
Website[id=3,name=百度,url=https://www.baidu.com/,age=18,country=CN]
上述代碼中,根據(jù)傳入的起始位置(currentPageNo=0)和頁面容量(pageSize=3)進(jìn)行相應(yīng)分頁,查看第一頁的數(shù)據(jù)列表,運(yùn)行測試方法,輸出正確的分頁列表。
注意:MyBatis 實(shí)現(xiàn)分頁查詢屬于 DAO 層操作,由于 DAO 層不牽涉任何業(yè)務(wù)實(shí)現(xiàn),所以實(shí)現(xiàn)分頁的方法中第一個參數(shù)為 limit 的起始位置(下標(biāo)從 0 開始),而不是用戶輸入的真正頁碼(頁碼從1開始)。在 JSP 教程的《JSP分頁》一節(jié)已經(jīng)學(xué)習(xí)過頁碼如何轉(zhuǎn)換為 limit 的起始位置下標(biāo),即:起始位置下標(biāo)=(頁碼-1)*頁面容量,那么這個轉(zhuǎn)換操作必然不能在 DAO 層實(shí)現(xiàn),需要在業(yè)務(wù)層實(shí)現(xiàn)。所以我們在測試類中傳入的參數(shù)為下標(biāo),而不是頁碼。