用limit实现分页,首先要创建一个Maven项目,搭建好mybatis的实验环境,并且连接好数据库
UserMapper
//查询全部用户实现分页
List<User> selectUser(Map<String,Integer> map);
startIndex:起始位置
startIndex=(currentPage-1)*pageSize
pageSize:页面大小
currentPage:当前页
<select id="selectUserByLimit" parameterType="Map" resultType="User">
select * from user limit #{startIndex},#{pageSize}
</select>
模拟分页数据:currentPage,pageSize
@Test
public void selectUser(){
<span class="hljs-comment">//创建sqlSession</span>
SqlSessionFactory sqlSessionFactory = MyBatisUtils.getSqlSessionFactory();
SqlSession sqlSession = sqlSessionFactory.openSession();
<span class="hljs-comment">//准备数据</span>
<span class="hljs-keyword">int</span> currentPage = <span class="hljs-number">1</span>;<span class="hljs-comment">//当前是第几页</span>
<span class="hljs-keyword">int</span> pageSize = <span class="hljs-number">2</span>; <span class="hljs-comment">//页面大小</span>
Map<String, Integer> <span class="hljs-built_in">map</span> = <span class="hljs-keyword">new</span> HashMap<String, Integer>();
<span class="hljs-built_in">map</span>.put(<span class="hljs-string">"startIndex"</span>,(currentPage<span class="hljs-number">-1</span>)*pageSize);
<span class="hljs-built_in">map</span>.put(<span class="hljs-string">"pageSize"</span>,pageSize);
<span class="hljs-comment">//测试</span>
UserDao mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.selectUserByLimit(<span class="hljs-built_in">map</span>);
<span class="hljs-keyword">for</span> (User user : users) {
System.out.println(user);
}
sqlSession.close();<span class="hljs-comment">//关闭连接</span>
可以为一个包的所有类指定别名,这个别名为类名
com.kuang.pojo.User - > User
写在你的mybatis配置文件下
<!--优化别名-->
<typeAliases>
<package name="com.Shandx.pojo"/>
</typeAliases>
手机扫一扫
移动阅读更方便
你可能感兴趣的文章