商品列表查询
1.在SqlMapConfig.xml中配置插件。
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration 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>
2.现在建一个测试类试一下分页数据,在Java文件夹上右击选择Mark Directory As 在扩展的框中选择Test Sources Root。
3.TestPageHelper类,内容如下:
import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.taotao.mapper.TbItemMapper; import com.taotao.pojo.TbItem; import com.taotao.pojo.TbItemExample; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.List; /** * Created by Administrator on 2018/5/2. */ public class TestPageHelper { @Test public void 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 (TbItem tbItem : list) { System.out.println(tbItem.getTitle()); } //取分页信息 PageInfo<TbItem> pageInfo = new PageInfo<>(list); long total = pageInfo.getTotal(); System.out.println("共有商品:"+ total); } }
4.在taotao-common中创建EUDateGridResult
内容如下:
package com.taotao.pojo; import java.util.List; /** * Created by Administrator on 2018/5/2. */ public class EUDataGridResult { private long total; private List<?> rows; public long getTotal() { return total; } public List<?> getRows() { return rows; } public void setTotal(long total) { this.total = total; } public void setRows(List<?> rows) { this.rows = rows; } }
5.在接口中添加
EUDataGridResult getItemList(Integer page, Integer rows);
6.在实现类中实现
@Override public EUDataGridResult getItemList(Integer page, Integer rows) { //查询商品列表 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()); return result; }
7.Controller
@RequestMapping("/item/list") @ResponseBody public EUDataGridResult getItemList(Integer page, Integer rows) { EUDataGridResult result = itemService.getItemList(page, rows); return result; }
8.结果测试