您的位置:首页 > 其它

Maven项目:PageHelper插件的使用

2018-02-07 11:14 405 查看
一、实现原理



二、实现步骤

第一步:引入pageHelper的jar包。

第二步:需要在SqlMapConfig.xml中配置插件。

<?xmlversion="1.0"encoding="UTF-8"?>

<!DOCTYPEconfiguration

          PUBLIC"-//mybatis.org//DTD Config 3.0//EN"

         
"http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

     <!--配置分页插件 -->

     <plugins>

         <plugin
interceptor="com.github.pagehelper.PageHelper">

              <!--
设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库-->       

         <property
name="dialect"value="mysql"/>

         </plugin>

     </plugins>

</configuration>

第三步:在查询的sql语句执行之前,添加一行代码:

PageHelper.startPage(1, 10);

第一个参数是page,要显示第几页。

第二个参数是rows,没页显示的记录数。

第四步:取查询结果的总数量。

创建一个PageInfo类的对象,从对象中取分页信息。

三、分布测试

publicclass TestPageHelper {
     @Test
     publicvoid testPageHelper() {
         
//创建一个spring容器
          ApplicationContext
applicationContext
=new ClassPathXmlApplicationContext("classpath:spring/applicationContext-*.xml");
         
//从spring容器中获得Mapper的代理对象
          TbItemMapper
mapper = applicationContext.getBean(TbItemMapper.class);
         
//执行查询,并分页
          TbItemExample
example = new TbItemExample();
         
//分页处理
          PageHelper.startPage(2, 10);
          List<TbItem>
list = mapper.selectByExample(example);
         
//取商品列表
          for (TbItemtbItem :
list) {
               System.out.println(tbItem.getTitle());
          }
         
//取分页信息
          PageInfo<TbItem>
pageInfo = new PageInfo<>(list);
          longtotal =pageInfo.getTotal();
          System.out.println("共有商品:"+total);
  
     }
}

四、实例

接收分页参数,一个是page一个是rows。调用dao查询商品列表。并分页。返回商品列表。

返回一个EasyUIDateGrid支持的数据格式。需要创建一个Pojo。此pojo应该放到taotao-common工程中。
publicclass EUDataGridResult {
     privatelongtotal;
     private List<?>rows;
     publiclong getTotal() {
          returntotal;
     }
     publicvoid setTotal(longtotal)
{
          this.total =total;
     }
     public List<?> getRows() {
          returnrows;
     }
     publicvoid setRows(List<?>rows)
{
          this.rows =rows;
     }
}

 public EUDataGridResult getItemList(intpage,introws)
{
         
//查询商品列表
          TbItemExample
example = new TbItemExample();
         
//分页处理
          PageHelper.startPage(page,rows);
          List<TbItem>
list = itemMapper.selectByExample(example);
         
//创建一个返回值对象
          EUDataGridResult
result = new EUDataGridResult();
         
result.setRows(list);
         
//取记录总条数
          PageInfo<TbItem>
pageInfo = new PageInfo<>(list);
         
result.setTotal(pageInfo.getTotal());
          returnresult;
     }

Controller层的实现

接收页面传递过来的参数page、rows。返回json格式的数据。EUDataGridResult

需要使用到@ResponseBody注解。

@RequestMapping("/item/list")
     @ResponseBody
     public
EUDataGridResult getItemList(Integer
page, Integer
rows) {
          EUDataGridResult
result = itemService.getItemList(page,
rows);
          returnresult;
     }

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐