共計 1949 個字符,預計需要花費 5 分鐘才能閱讀完成。
自動寫代碼機器人,免費開通
Oracle 中分頁查詢因為存在偽列 rownum,sql 語句寫起來較為復雜,現在介紹一種通過使用 MyBatis 中的 RowBounds 進行分頁查詢,非常方便。
使用 MyBatis 中的 RowBounds 進行分頁查詢時,不需要在 sql 語句中寫 offset,limit,mybatis 會自動拼接 分頁 sql,添加 offset,limit,實現自動分頁。
需要前臺傳遞參數 currentPage 和 pageSize 兩個參數,分別是當前頁和每頁數量,controller 層把參數傳遞給 service 層即可,下面是 service 實現的代碼:
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) {
// 查詢數據總條數
int total = userDao.queryCountUser();
// 返回結果集
Map String,Object resultMap = new HashMap String,Object
resultMap.put("total", total);
// 總頁數
int totalpage = (total + Integer.parseInt(pageSize) - 1) / Integer.parseInt(pageSize);
resultMap.put("totalpage", totalpage);
// 數據的起始行
int offset = (Integer.parseInt(currentPage)-1)*Integer.parseInt(pageSize);
RowBounds rowbounds = new RowBounds(offset, Integer.parseInt(pageSize));
// 用戶數據集合
List Map String, Object userList = userDao.queryUserList(rowbounds);
resultMap.put("userList", userList);
return resultMap;
}
dao 層接口:
package com.xyfer.dao;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.RowBounds;
public interface UserDao {public int queryCountUser(); // 查詢用戶總數
public List Map String, Object queryUserList(RowBounds rowbounds); // 查詢用戶列表
}
對應的 mapper.xml 文件:
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"
!-- 查詢用戶總數 --
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 調用接口,傳入對應的參數,即可實現分頁查詢數據。
總結
以上所述是丸趣 TV 小編給大家介紹的 Oracle 使用 MyBatis 中 RowBounds 實現分頁查詢功能, 希望對大家有所幫助,如果大家有任何疑問請給我留言,丸趣 TV 小編會及時回復大家的。在此也非常感謝大家對丸趣 TV 網站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請注明出處,謝謝!
向 AI 問一下細節
丸趣 TV 網 – 提供最優質的資源集合!
正文完