分页
1.通过limit实现分页
操作sql进行分页
select * from user limit 0,2; #从第0个开始,每页展示两个
在mybatis中
通过传入参数对limit的两个值进行更改
-
mapper接口
//分页查找城市 List<City> cityLimit(Map<String,Object> map);
-
xml配置文件
<select id="cityLimit" parameterType="map" resultMap="city"> select * from jdbcstudy.city limit #{startIndex},#{pageSize}; </select>
-
测试类
public void cityTest01(){ SqlSession sqlSession = SqlSessionUtils.getSqlSession(); CityMapper mapper = sqlSession.getMapper(CityMapper.class); Map<String,Object> map = new HashMap<>(); map.put("startIndex",0); map.put("pageSize",3); List<City> cities = mapper.cityLimit(map); for (City city : cities) { System.out.println(city); } sqlSession.close(); }
本质是通过map将参数传递给sql
2.RowBounds分页
通过sql分页,不能体现面向对象的特点,所以有些开发人员写了RowBounds这个类,来实现分页
实际还是limit分页
具体实现:
-
接口
//RowBounds实现分页 List<City> cityRowBounds();
-
xml配置文件
<select id="cityRowBounds" resultType="city"> select * from jdbcstudy.city; </select>
-
测试类
public void cityTest02(){ SqlSession sqlSession = SqlSessionUtils.getSqlSession(); RowBounds rowBounds = new RowBounds(0, 3); List<Object> objects = sqlSession.selectList("com.wang.Dao.CityMapper.cityRowBounds", null, rowBounds); for (Object object : objects) { System.out.println(object); } sqlSession.close(); }
在测试类中,new 一个rowBounds类,参数就是(从第几个开始)和(每页有几个)
然后通过sqlSession调用selectList方法,参数为:Mapper接口的方法、Object、rowBounds