Mybatis分页查询


思考:为什么要分页?
减少数据的处理量
1、使用Limit分页
语法:

select * from user limit startIndex,pageSize;
select * from user limit 3;#[0,n]

使用Mybatis实现分页,核心SQL
接口

  /**
  * 分页查询
  * @return
  */
  List<User> getUserByLimt(Map<String,Integer> map);

Mapper.xml

    //测试
    public void getUserByLimt(){
        SqlSession sqlsession = MybatisUtil.getSqlsession();
        UserMapper mapper = sqlsession.getMapper(UserMapper.class);
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        map.put("startIndex",0);
        map.put("pageSize",3);
        List<User> userByLimt = mapper.getUserByLimt(map);
        for (User user : userByLimt) {
            System.out.println(user);
        }
    }

2、RowBounds分页
不在使用SQL实现分页

接口

 /**
 *
 * @return
 */
 List<User> getUserByRowBounds();
Mapper.xml
<select id="getUserByRowBounds" resultMap="UserMap">
    select * from mybatis.user
</select>
  //测试
public void getUserByRowBounds(){
    SqlSession sqlsession = MybatisUtil.getSqlsession();
    //RowBounds实现
   RowBounds rowBounds = new RowBounds(1, 2);
   //通过java层面实现分页
   List<User> list = sqlsession.selectList("com.aostarit.dao.UserMapper.getUserByRowBounds",null,rowBounds);
   for (User user : list) {
       System.out.println(user);
    }
   //关闭sqlSession
   sqlsession.close();
}
上一篇:使用MyBatis小记


下一篇:Mybatis 执行器