MyBatis(五):分页

本文是按照狂神说的教学视频学习的笔记,强力推荐,教学深入浅出一遍就懂!b站搜索狂神说或点击下面链接

https://space.bilibili.com/95256449?spm_id_from=333.788.b_765f7570696e666f.2

Limit实现分页

  • 提醒:不要忘了应该把SqlSession对象放在finily要关闭!本文为了方便省去这步!

  • 实体类

package com.rzp.pojo;
​
public class User {
    private int id;
    private String name;
    private String pwd;
 //有参+无参构造+get+set+toString
}
​

 

  • Mapper.xml

   <select id="getUserByLimit" parameterType="map" resultType="user">
        select * from mybatis.user limit #{startIndex},#{pageSize}
    </select>

 

  • Mapper接口

public interface UserMapper {
    //分页
    List<User> getUserByLimit(Map<String,Integer> map);
}

 

  • 测试方法

   @Test
    public void getUserByLimit(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //使用map传参数,通过sql的limit条件实现分页
        HashMap<String, Integer> map = new HashMap<>();
        map.put("startIndex",0);
        map.put("pageSize",2);
        List<User> userList = mapper.getUserByLimit(map);
        for (User user : userList) {
            System.out.println(user.toString());
        }
        sqlSession.close();
    }

 

RowBounds

  • 好处:符合面向对象的规范

  • 坏处:先查询了所有,占用资源太多;使用的sqlSession.selectList的方法,该方法比较旧,官方不推荐使用。

  • Mapper.xml

   <select id="getUserByRowBounds" resultType="user">
        select * from mybatis.user
    </select>

 

  • Mapper接口

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

 

  • 测试方法

   @Test //RowBounds分页
    public void getUserByRowBounds(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //RowBounds实现
        RowBounds rowBounds = new RowBounds(0, 2);
        //传入rowBounds
        List<User> userList = sqlSession.selectList("com.rzp.dao.UserMapper.getUserByRowBounds",null,rowBounds);
        for (User o : userList) {
            System.out.println(o.toString());
        }
        sqlSession.close();
    }

 

 

posted @ 2020-03-28 00:12  renzhongpei  阅读(215)  评论(0编辑  收藏  举报