MyBatis limit分頁設(shè)置的實(shí)現(xiàn)
<select parameterType='MyApplicationRequest' resultMap='myApplicationMap'> SELECT a.*, FROM tb_user a WHERE 1=1 <if test='ids != null and ids.size()!=0'> AND a.id IN <foreach collection='ids' item='id' index='index' open='(' close=')' separator=','> #{id} </foreach> </if> <if test='statusList != null and statusList.size()!=0'> AND a.status IN <foreach collection='statusList' item='status' index='index' open='(' close=')' separator=','> #{status} </foreach> </if> ORDER BY a.create_time desc LIMIT (#{pageNo}-1)*#{pageSize},#{pageSize}; // 錯(cuò)誤</select>
在MyBatis中LIMIT之后的語句不允許的變量不允許進(jìn)行算數(shù)運(yùn)算,會報(bào)錯(cuò)。
正確的寫法一:<select parameterType='MyApplicationRequest' resultMap='myApplicationMap'> SELECT a.*, FROM tb_user a WHERE 1=1 <if test='ids != null and ids.size()!=0'> AND a.id IN <foreach collection='ids' item='id' index='index' open='(' close=')' separator=','> #{id} </foreach> </if> <if test='statusList != null and statusList.size()!=0'> AND a.status IN <foreach collection='statusList' item='status' index='index' open='(' close=')' separator=','> #{status} </foreach> </if> ORDER BY a.create_time desc LIMIT ${(pageNo-1)*pageSize},${pageSize}; (正確)</select> 正確的寫法二:(推薦)
<select parameterType='MyApplicationRequest' resultMap='myApplicationMap'> SELECT a.*, FROM tb_user a WHERE 1=1 <if test='ids != null and ids.size()!=0'> AND a.id IN <foreach collection='ids' item='id' index='index' open='(' close=')' separator=','> #{id} </foreach> </if> <if test='statusList != null and statusList.size()!=0'> AND a.status IN <foreach collection='statusList' item='status' index='index' open='(' close=')' separator=','> #{status} </foreach> </if> ORDER BY a.create_time desc LIMIT #{offSet},#{limit}; (推薦,代碼層可控)</select>
分析:方法二的寫法,需要再請求參數(shù)中額外設(shè)置兩個(gè)get函數(shù),如下:
@Datapublic class QueryParameterVO { private List<String> ids; private List<Integer> statusList; // 前端傳入的頁碼 private int pageNo; // 從1開始 // 每頁的條數(shù) private int pageSize; // 數(shù)據(jù)庫的偏移 private int offSet; // 數(shù)據(jù)庫的大小限制 private int limit; // 這里重寫offSet和limit的get方法 public int getOffSet() { return (pageNo-1)*pageSize; } public int getLimit() { return pageSize; }}
到此這篇關(guān)于MyBatis limit分頁設(shè)置的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)MyBatis limit分頁內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. Mysql分組排序取每組第一條的2種實(shí)現(xiàn)方式2. Windows系統(tǒng)徹底卸載SQL Server通用方法(推薦!)3. Sql在多張表中檢索數(shù)據(jù)的方法詳解4. SQL Server數(shù)據(jù)庫創(chuàng)建表及其約束條件的操作方法5. MySQL5.7 mysqldump備份與恢復(fù)的實(shí)現(xiàn)6. MYSQL(電話號碼,身份證)數(shù)據(jù)脫敏的實(shí)現(xiàn)7. Mysql中的日期時(shí)間函數(shù)小結(jié)8. mysql查詢的控制語句圖文詳解9. MySql中sql語句執(zhí)行過程詳細(xì)講解10. 根據(jù)IP跳轉(zhuǎn)到用戶所在城市的實(shí)現(xiàn)步驟
