MyBatis limit分頁設(shè)置的實現(xiàn)
更新時間:2021年04月04日 11:30:12 作者:timchen525
這篇文章主要介紹了MyBatis limit分頁設(shè)置的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
錯誤的寫法:
<select id="queryMyApplicationRecord" 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之后的語句不允許的變量不允許進行算數(shù)運算,會報錯。
正確的寫法一:
<select id="queryMyApplicationRecord" 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 id="queryMyApplicationRecord" 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è)置兩個get函數(shù),如下:
@Data
public 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è)置的實現(xiàn)的文章就介紹到這了,更多相關(guān)MyBatis limit分頁內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解Java從后臺重定向(redirect)到另一個項目的方法
這篇文章主要介紹了詳解Java從后臺重定向(redirect)到另一個項目的方法,非常具有實用價值,需要的朋友可以參考下2017-04-04
springboot項目攔截前端請求中的特殊字符串(解決方案)
springboot項目中,需要對前端請求數(shù)據(jù)進行過濾,攔截特殊字符,本文通過實例代碼給大家分享完美解決方案,感興趣的朋友一起看看吧2023-10-10
Spring中@Configuration注解和@Component注解的區(qū)別詳解
這篇文章主要介紹了Spring中@Configuration注解和@Component注解的區(qū)別詳解,@Configuration 和 @Component 到底有何區(qū)別呢?我先通過如下一個案例,在不分析源碼的情況下,小伙伴們先來直觀感受一下這兩個之間的區(qū)別,需要的朋友可以參考下2023-09-09

