最近在作宜立方商城项目时,后台管理系统要求实现分页显示,因为项目使用了Mybatis逆向生成映射文件,因此在此使用了mybatis第三方插件--PageHelper来实现分页这一功能,下面就如何在项目使用这一插件进行说明。
pagehelper-fix下载连接:连接:https://pan.baidu.com/s/1kXb1OF1 密码:tgk5java
2.修改mybatis配置文件mysql
在Mybatis配置xml中配置拦截器插件: <plugins> <!-- com.github.pagehelper为PageHelper类所在包名 --> <plugin interceptor="com.github.pagehelper.PageHelper"> <!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库--> <property name="dialect" value="mysql"/> </plugin> </plugins>
3. 如何在项目中使用PageHelpergit
import java.util.List; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import cn.e3mall.mapper.TbItemMapper; import cn.e3mall.pojo.TbItem; import cn.e3mall.pojo.TbItemExample; /** * @author 熊涛 *分页测试用例 */ public class PageHelperTest { @Test public void testPageHelper() throws Exception { //初始化spring容器 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-*.xml"); //得到Mapper的代理对象 TbItemMapper itemMapper = applicationContext.getBean(TbItemMapper.class); //执行sql语句前设置分页信息使用PageHelper的startPage方法 PageHelper.startPage(1,30); //执行查询 TbItemExample example = new TbItemExample(); List<TbItem> list = itemMapper.selectByExample(example); //取分页信息,PageInfo:1.总记录数 2.总页数 3.当前页码 PageInfo<TbItem> pageInfo = new PageInfo<>(list); System.out.println(pageInfo.getTotal()); System.out.println(pageInfo.getPages()); System.out.println(pageInfo.getPageNum()); System.out.println(pageInfo.getPageSize()); } }
4. 在服务层使用PageHelpergithub
@Override public EasyUIDataGridResult getItemList(int page, int rows) { //设置分页信息 PageHelper.startPage(page, rows); //执行查询 TbItemExample example = new TbItemExample(); List<TbItem> list = itemMapper.selectByExample(example); //取分页信息 PageInfo<TbItem> pageInfo = new PageInfo<>(list); //建立返回结果对象 EasyUIDataGridResult result = new EasyUIDataGridResult(); result.setTotal(pageInfo.getTotal()); result.setRows(list); return result; }
5. 在控制层使用servicespring
@RequestMapping("/item/list")
@ResponseBody
public EasyUIDataGridResult getItemList(Integer page, Integer rows) {sql
EasyUIDataGridResult result = itemService.getItemList(page, rows); return result;
}数据库