一. MyBatis 的分页查询
在以往的查询中,都没有牵扯到关于分页查询的知识,主要留在最后讲述一下 pageHelper 分页插件的使用。
在MySQL 中,分页时用 limit start,offset 即可以进行相应的查询。
还是用以前的User 表进行举例,只是多了几条数据。
其中,User.java 对象是MyBatis的逆向工程自动生成的,还有一个UserExample.java 对象。
至于逆向工程,可以参考本系列下的: MyBatis逆向工程的使用(十二)
二. 以前的分页查询,拼接sql 语句。
UserMapper.java 接口:
//根据limit 语句拼接,进行相应的分页 List<User> selectBySQL(@Param(value="start")int start, @Param(value="offset") int offset);
UserMapper.xml sql语句:
<!-- 分页查询 --> <select id="selectBySQL" resultMap="BaseResultMap" parameterType="com.yjl.pojo.UserExample" > select <include refid="Base_Column_List" /> from user limit #{start},#{offset} </select>
测试方法:
@Test public void test1(){ SqlSession sqlSession=SqlSessionFactoryUtils.getSession(); UserMapper userMapper=sqlSession.getMapper(UserMapper.class); int page=2; int rowNum=5; int start=(page-1)*maxRow; List<User> allUser=userMapper.selectBySQL(start,rowNum); allUser.forEach(n ->System.out.println(n)); }
可以看到,是用的limit 直接进行的分页查询。
但是这种分页是放置在sql 语句里面的, 很可能每一个查询的sql 语句都要在最后添加 一下这个语句,并且还非得传入两个参数,可重复利用性低,尤其是条件查询时。 故最好,不采用这种方式进行分页。
三. 在XxxExample.java 中添加 分页的两个字段 start 和offset
在UserExample.java 中添加start 和offset的字段,用于分页查询,并且实现setter和getter方法。
//添加两个字段,用于分页。 private int start; //开始的位置 private int offset; //每页显示的最大数目
那么,在多条件查询语句,即
List<User> selectByExample(UserExample example);
接口时,改变相应的sql 实现,添加其中的分页显示。
<select id="selectByExample" resultMap="BaseResultMap" parameterType="com.yjl.pojo.UserExample" > select <if test="distinct" > distinct </if> <include refid="Base_Column_List" /> from user <if test="_parameter != null" > <include refid="Example_Where_Clause" /> </if> <if test="orderByClause != null" > order by ${orderByClause} </if> <!-- 利用choose,添加分页的处理 --> <choose> <when test="start!=0 and offset!=0"> limit ${start},${offset} </when> <when test="start==0 and offset!=0"> limit 0,${offset} </when> <otherwise> <!-- 不执行任何操作。 --> </otherwise> </choose> </select>
测试方法:
@Test public void test2(){ SqlSession sqlSession=SqlSessionFactoryUtils.getSession(); UserMapper userMapper=sqlSession.getMapper(UserMapper.class); UserExample example=new UserExample(); example.setOrderByClause("id asc"); //设置分页。 int page=2; int rowNum=5; int start=(page-1)*rowNum; example.setStart(start); //设置开始点 example.setOffset(rowNum); //设置每页显示的个数 List<User> allUser=userMapper.selectByExample(example); allUser.forEach(n ->System.out.println(n)); }
全部打开时,显示:
将 example.setStart(start); 注释掉:
将 example.setOffset(rowNum); 也注释掉:
这样,就完成了有查询条件的分页。
但是,这样也有问题,如果没有查询条件,或者是没有用UserExample 类的是没有办法进行分页的。
改进 用 MyBatis 自带的 RowBounds 类。