• Oracle使用MyBatis中RowBounds实现分页查询


    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调用接口,传入对应的参数,即可实现分页查询数据。

  • 相关阅读:
    python正则表达式基础,以及pattern.match(),re.match(),pattern.search(),re.search()方法的使用和区别
    python正则表达式--分组、后向引用、前(后)向断言
    python正则表达式--flag修饰符、match对象属性
    mybatis-核心配置文件和mappe.xml
    mybatis mapper标签
    spring JdbcTemplate 常用的自定义工具包
    web基础
    8.24 JDBC 调用存储过程
    8.24 事务处理
    8.24 批处理
  • 原文地址:https://www.cnblogs.com/xyfer1018/p/11208672.html
Copyright © 2020-2023  润新知