当我们使用Mybatis实现分页操作时,我们需要注意Mybatis逻辑分页与物理分页这两个区别
逻辑分页:将数据一次性从数据库查出到内存中,在内存中进行逻辑上的分页
物理分页:直接特定的SQL语句,只从数据库中查询出需要的数据
mybatis自带分页RowBounds: //逻辑分页
业务逻辑代码
public List<User> findUserByPage() {
//
TODO Auto-generated method stub
SqlSession sqlSession =
ssf.openSession();
int offSet = 0;
int limit = 2;
User user =
new User();
user.setName("qing");
RowBounds rowRounds =
new RowBounds(offSet, limit);
List<User> listUsers = sqlSession.selectList("select UserByPage", user, rowRounds);
return listUsers;
}
<select id="selectUserByPage" resultType="test_ibatis.User"
resultSetType="SCROLL_SENSITIVE"parameterType="test_ibatis.User">
select * from t_user where name like '%'||#{name}||'%'
</select>
mybatis自写sql或者通过分页插件PageHelper: //物理分页
分页插件PageHelper
Service层:
PageHelper.startPage(pageNum,pageSize);//pageNum 页数 pageSize 数量
List<Student> stu=studentDao.findStudent(); //studentDao @Autowried注解获取; 在执行查询数据时,就会自动执行2个sql;执行上述Mapper下的ID为findStudent的sql 自动执行分页,通过PageHelper进行识别是何数据库拼接分页语句,若是mysql,自动通过limit分页,若是oracle自动通过rownum进行分页,另一个会自动拼接Mapper下不存在的ID为findStudent_COUNT,查询的总数;可以通过打印的日志进行跟踪;
PageInfo<Student> page = new PageInfo<Student>(stu); //自动封装总数count以及分页,数据返回页面
return page;//返回分页之后的数据
Dao层-StudentDao:
List findStudent();
Mapper:
<select id="findStudent" resultType="Student">
select * from Student
</select>
Mybatis 自己写SQL进行分页
。。。。。。。。。
总结:
1:逻辑分页 内存开销比较大,在数据量比较小的情况下效率比物理分页高;在数据量很大的情况下,内存开销过大,容易内存溢出,不建议使用
2:物理分页 内存开销比较小,在数据量比较小的情况下效率比逻辑分页还是低,在数据量很大的情况下,建议使用物理分页