一. Mysql分页
Mysql可以LIMIT关键字进行分页,比如从第1条开始,查询4条:
SELECT * FROM xxx LIMIT 0,4
规律为:比如要从第x条开始,查y条,则sql语句为:
SELECT * FROM xxx LIMIT (x-1) , y
每个sql语句为一页,则第n页为
SELECT * FROM xxx LIMI y * (n-1) , y
二. 使用Mybatis插件分页
Mybatis插件为各种数据库都提供了强大的分页功能支持。这里以Mysql为例:
11. 在Maven的pom.xml中添加以下依赖:
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.1.10</version> </dependency>
2. 配置拦截器插件
在application的SqlSessionFactoryBean中添加以下内容
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> ........ <property name="plugins"> <array> <bean class="com.github.pagehelper.PageInterceptor"> <property name="properties"> <props> <prop key="helperDialect">mysql</prop> </props> </property> </bean> </array> </property> </bean>
3. 在service中完成分页
@Override public List<Map<String, Object>> query(String name, Integer cid, Integer bid, Integer page) { Map<String,Object> param = new HashMap<>(); param.put("cid",cid); param.put("bid",bid); param.put("name",name); //开始分页 PageHelper.startPage(page,4); List<Map<String, Object>> products = productMapper.query(param); /*System.out.println("-----------------------"); System.out.println(products.size()); System.out.println("------------"); System.out.println(products.getClass()); //此时的products已经是一个Page类 for (Map<String, Object> product : products) { System.out.println("product = " + product); } System.out.println("-----------------------");*/ return products; }
4. Controller
@Controller public class ProductController { @Autowired private ProductService productService; @GetMapping("/list") public String list(String name, Integer cid, Integer bid, @RequestParam(required = false,defaultValue = "1") Integer page, Model model){ List<Map<String, Object>> products = productService.query(name, cid, bid, page); model.addAttribute("products",products); if(products instanceof Page){ Page productPage = (Page) products; //当前页数 int pageNum = productPage.getPageNum(); //总页数 int pages = productPage.getPages(); model.addAttribute("pageNum",pageNum); model.addAttribute("pages",pages); } return "list"; } }
请登录之后再进行评论