Oracle中分頁查詢因為存在偽列rownum,sql語句寫起來較為復(fù)雜,現(xiàn)在介紹一種通過使用MyBatis中的RowBounds進(jìn)行分頁查詢,非常方便。
使用MyBatis中的RowBounds進(jìn)行分頁查詢時,不需要在 sql 語句中寫 offset,limit,mybatis 會自動拼接 分頁sql ,添加 offset,limit,實(shí)現(xiàn)自動分頁。
需要前臺傳遞參數(shù)currentPage和pageSize兩個參數(shù),分別是當(dāng)前頁和每頁數(shù)量,controller層把參數(shù)傳遞給service層即可,下面是service實(shí)現(xiàn)的代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
package com.xyfer.service.impl; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.ibatis.session.RowBounds; import com.xyfer.dao.UserDao; import com.xyfer.service.UserService; public class UserServiceImpl implements UserService { private UserDao userDao; @Override public Map<String, Object> queryUserList(String currentPage, String pageSize) { //查詢數(shù)據(jù)總條數(shù) int total = userDao.queryCountUser(); //返回結(jié)果集 Map<String,Object> resultMap = new HashMap<String,Object>(); resultMap.put( "total" , total); //總頁數(shù) int totalpage = (total + Integer .parseInt(pageSize) - 1) / Integer .parseInt(pageSize); resultMap.put( "totalpage" , totalpage); //數(shù)據(jù)的起始行 int offset = ( Integer .parseInt(currentPage)-1)* Integer .parseInt(pageSize); RowBounds rowbounds = new RowBounds(offset, Integer .parseInt(pageSize)); //用戶數(shù)據(jù)集合 List<Map<String, Object>> userList = userDao.queryUserList(rowbounds); resultMap.put( "userList" , userList); return resultMap; } } |
dao層接口:
1
2
3
4
5
6
7
8
|
package com.xyfer.dao; import java.util.List; import java.util.Map; import org.apache.ibatis.session.RowBounds; public interface UserDao { public int queryCountUser(); //查詢用戶總數(shù) public List<Map<String, Object>> queryUserList(RowBounds rowbounds); //查詢用戶列表 } |
對應(yīng)的mapper.xml文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<?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.xyfer.mapper.UserMapper" > <! -- 查詢用戶總數(shù) --> < select id= "queryCountUser" resultType= "java.lang.Integer" > select count (1) from user </ select > <! -- 查詢用戶列表 --> < select id= "queryUserList" resultType= "java.util.Map" > select * from user </ select > </mapper> |
通過postman調(diào)用接口,傳入對應(yīng)的參數(shù),即可實(shí)現(xiàn)分頁查詢數(shù)據(jù)。
總結(jié)
以上所述是小編給大家介紹的Oracle使用MyBatis中RowBounds實(shí)現(xiàn)分頁查詢功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對服務(wù)器之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
原文鏈接:https://www.cnblogs.com/xyfer1018/archive/2019/07/18/11208672.html