MyBatis limit分頁設置的實現
<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>
在MyBatis中LIMIT之后的語句不允許的變量不允許進行算數運算,會報錯。
正確的寫法一:<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>
分析:方法二的寫法,需要再請求參數中額外設置兩個get函數,如下:
@Datapublic class QueryParameterVO { private List<String> ids; private List<Integer> statusList; // 前端傳入的頁碼 private int pageNo; // 從1開始 // 每頁的條數 private int pageSize; // 數據庫的偏移 private int offSet; // 數據庫的大小限制 private int limit; // 這里重寫offSet和limit的get方法 public int getOffSet() { return (pageNo-1)*pageSize; } public int getLimit() { return pageSize; }}
到此這篇關于MyBatis limit分頁設置的實現的文章就介紹到這了,更多相關MyBatis limit分頁內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
1. Access數據庫安全的幾個問題2. 快速掌握Oracle數據庫游標的使用方法3. 如何實現MySQL數據庫的備份與恢復4. MySQL Community Server 5.1.495. 數據庫Oracle9i的企業管理器簡介6. MySQL InnoDB 鎖的相關總結7. 簡單了解mysql語句書寫和執行順序8. Mysql故障排除:Starting MySQL. ERROR! Manager of pid-file quit without updating file9. DB2 與 Microsoft SQL Server 2000 之間的 SQL 數據復制10. Access中批量替換數據庫內容的兩種方法
