Limit 分页:
startIndex 起始位置,pageSize 每页显示个数
select * from mybatis.`user` limit startIndex,pageSize;
比如 limit 0,2;
从第零个开始查,每页显示两个(如果第一个数字是 1,其实是从第二条数据开始展示)
如果 limit 后只有一个数(比如 limit 3;),即显示这个数的数据条数(显示 3 条数据)
UserMapper 接口:写个方法
User 类是根据表字段设置的变量,无参、有参、get/set 方法
package com.demo.dao;import com.demo.pojo.User;import java.util.List;
import java.util.Map;public interface UserMapper {//分页List<User> getUserByLimit(Map<String,Integer> map);
}
UserMapper.xml:
id 与接口名一致
parameterType 参数类型为 map
resultType 返回结果为 sql 语句的全限定名(设了 typeAliases 别名)
<!-- 分页 --><select id="getUserByLimit" parameterType="map" resultType="user">select * from mybatis.user limit #{startIndex},#{pageSize}</select>
测试类:
构造 map,new 一个 HashMap
通过 put 方法设置起始位置和页面展示个数
遍历数组输出查询结果
最后关闭 sqlSession,避免造成资源浪费
package com.demo.dao;import com.demo.pojo.User;
import com.demo.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;import java.util.HashMap;public class UserDaoTest {@Testpublic void getUserByLimit(){SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);HashMap<String,Integer> map = new HashMap<String, Integer>();map.put("startIndex",0);map.put("pageSize",2);for (User user : mapper.getUserByLimit(map)) {System.out.println(user);}sqlSession.close();}
}
RowBounds 分页:(面向对象)
UserMapper 接口:
package com.demo.dao;import com.demo.pojo.User;import java.util.List;public interface UserMapper {List<User> getUserByRowBounds();
}
UserMapper.xml:
<select id="getUserByRowBounds" resultType="user">select * from mybatis.user</select>
测试类:
package com.demo.dao;import com.demo.pojo.User;
import com.demo.utils.MybatisUtils;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;import java.util.List;public class UserDaoTest {@Testpublic void getUserByRowBounds(){SqlSession sqlSession = MybatisUtils.getSqlSession();//RowBounds实现RowBounds rowBounds = new RowBounds(1,3);//通过Java代码层实现分页List<User> userList = sqlSession.selectList("com.demo.dao.UserMapper.getUserByRowBounds",null,rowBounds);for(User user:userList){System.out.println(user);}sqlSession.close();}
}
Mybatis 同时也提供了分页插件 PageHelper,详情查看链接
如何使用分页插件