用limit实现分页,首先要创建一个Maven项目,搭建好mybatis的实验环境,并且连接好数据库
代码
1,编写dao接口
UserMapper
//查询全部用户实现分页
List<User> selectUser(Map<String,Integer> map);
2,编写对应Mapper映射文件的方法
startIndex:起始位置
startIndex=(currentPage-1)*pageSize
pageSize:页面大小
currentPage:当前页
<select id="selectUserByLimit" parameterType="Map" resultType="User">
select * from user limit #{startIndex},#{pageSize}
</select>
3,测试
模拟分页数据: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>