mybatis-paginator+mysql 简单案例

来源:互联网 发布:淘宝和田玉店铺 编辑:程序博客网 时间:2024/06/15 20:43

接手一个旧项目,里面的mybatis使用了github上面的mybatis-paginator分页插件。看着旧代码摸不着头脑,所以复制了网上的一个案例,没想到一直跑不起来。down了源码才搞清楚,这里记录一下过程,备忘。

  • 如果要在界面使用jstl就要加拦截器,插件会自动给我返回的xxx对象上加Paginator一并返回来,eg:“上一页: ${xxxPaginator.prePage}”

springmvc.xml

<mvc:interceptors>    <mvc:interceptor>        <mvc:mapping path="/**"/>        <bean class="com.github.miemiedev.mybatis.paginator.springmvc.PageListAttrHandlerInterceptor"/>    </mvc:interceptor></mvc:interceptors>
  • dialect类包括了oracle,mysql,DB数据库,mybatis-config.xml引入的时候要注意,这里搞了半天,我说为什么我mysql的sql语句一直是oracle的rownum……

mybatis-config.xml

<configuration>    <plugins>        <plugin interceptor="com.github.miemiedev.mybatis.paginator.OffsetLimitInterceptor">            <property name="dialectClass" value="com.github.miemiedev.mybatis.paginator.dialect.MySQLDialect"/>        </plugin>    </plugins></configuration>
  • controller层

生成PageBounds 对象,构造方法很多,new对象的时候看看就知道了,很通俗易懂
调用Dao的sql方法的时候把PageBounds也传过去即可

eg:PageList继承了ArrayList,所以可以强转,里面包含了一个Paginator对象,有各种各样的属性,jsp页面取得时候按属性取即可。

@RequestMapping(value = "userPage",method = RequestMethod.GET)  public ModelAndView userPage(Integer page, Integer limit){      PageBounds pb = new PageBounds(page,limit);      List list = userMapper.userList(pb);      PageList pageList = (PageList)list;      return new ModelAndView("userPage.jsp","users", pageList);  }
  • Dao层 eg: xxx.selectList(“UserMapper.userList”,params,pageBounds);

params是自己的参数,pageBounds是controller穿过来的分页对象。如果不传自己的参数把第二个params去掉的话一直没有响应,这里估计是专门设置成这样的,所以给了一个空参数。

  • jsp 注意:key+Paginator是默认的返回方式,我传回来的key是users,插件就默认usersPaginator作为分页对象的key了。

“` jsp

<body>    <table>        <c:forEach items="${users}" var="user">            <tr>                <td>${user.id}</td>                <td>${user.user_name}</td>                <td>${user.password}</td>            </tr>        </c:forEach>    </table>    上一页: ${usersPaginator.prePage}    当前页: ${usersPaginator.page}    下一页: ${usersPaginator.nextPage}    总页数: ${usersPaginator.totalPages}    总条数: ${usersPaginator.totalCount}    更多属性参考Paginator类提供的方法</body>
  • 输出效果

插件开发者的文档写的就比较全面了,可以自行参考。
地址:https://github.com/miemiedev/mybatis-paginator

0 0
原创粉丝点击