分享

7 LIMIT分页

 路人甲Java 2021-07-01

LIMIT分页

为什么需要分页?

在对数据库进行大量数据查询时,往往需要使用分页进行查询,每次处理小部分数据,这样对数据库的压力在可控范围内。

使用LIMIT分页的常用语法

#数据库索引是从0开始
SELECT * FROM table LIMIT stratIndex,pageSize

SELECT * FROM table LIMIT 5,10; // 检索记录行 6-15  

#为了检索从某一个偏移量到记录集的结束所有的记录行,可以指定第二个参数为 -1,在最小的mysql版本中,该语法可以使用
SELECT * FROM table LIMIT 95,-1; // 检索记录行 96-last.  

#如果只给定一个参数,它表示返回最大的记录行数目:   
SELECT * FROM table LIMIT 5; //检索前 5 个记录行  

#换句话说,LIMIT n 等价于 LIMIT 0,n。 

使用LIMIT进行分页:

步骤:

1、在UserMapper.java接口中,编写函数

    // 分页查询
    List<User> getUserByLimit(Map map);

2、编写UserMapper.xml文件,传入参数类型为map

    <resultMap id="UserResult" type="User">
        <!-- column是数据库表的列名 , property是对应实体类的属性名 -->
        <id column="id" property="id"/>
        <result column="name" property="username"/>
        <result column="pwd" property="password"/>
    </resultMap>

    <select id="getUserByLimit" parameterType="map" resultMap="UserResult">
        SELECT * FROM user LIMIT #{startIndex}, #{pageSize}
    </select>

3、测试

    @Test
    public void getUserByLimit(){
        SqlSession sqlSession = MyBatisTool.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        // 分页,查询第一页,页面大小为2
        int pageIndex = 1;
        int pageSize = 2;
        // 用map准备参数
        Map<String, Integer> map = new HashMap<String, Integer>();
        //计算起始索引
        int startIndex = (pageIndex - 1) * pageSize;
        map.put("startIndex", startIndex);
        map.put("pageSize", pageSize);
        // 执行查询
        List<User> userList = mapper.getUserByLimit(map);
        for (User user : userList) {
            System.out.println(user);
        }

        sqlSession.close();
    }

使用RowBounds分页:【了解】

我们除了使用Limit在SQL层面实现分页,也可以使用RowBounds在Java代码层面实现分页。

1、在UserMapper.java接口中,编写函数

    // RowBounds分页
    List<User> getUserListByRowBounds();

2、编写UserMapper.xml文件,传入参数类型为map

    <resultMap id="UserResult" type="User">
        <!-- column是数据库表的列名 , property是对应实体类的属性名 -->
        <id column="id" property="id"/>
        <result column="name" property="username"/>
        <result column="pwd" property="password"/>
    </resultMap>

    <select id="getUserListByRowBounds" resultMap="UserResult">
        SELECT * FROM user
    </select>

3、测试

    @Test
    public void getUserListByRowBounds(){
        SqlSession sqlSession = MyBatisTool.getSqlSession();
        int pageIndex = 1;
        int pageSize = 2;
        RowBounds rowBounds = new RowBounds((pageIndex - 1) * pageSize, pageSize);
        List<User> userList = sqlSession.selectList("com.bg.mapper.UserMapper.getUserListByRowBounds", null, rowBounds);
        for (User user : userList) {
            System.out.println(user);
        }

        sqlSession.close();
    }

使用插件进行分页:

PageHelper自行了解。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多