SpringBoot Mybatis分页查询功能。

本文介绍如何使用MyBatis的分页插件PageHelper进行高效分页查询,包括配置步骤、代码实现及效果展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Mybatis是自带分页查询功能的哟。就不用自己再写一大堆算法实体类啥的,不多说直接上代码,并且我可愿意保证是100%能测试的哟。

1. 首先我们需要配置Mybatis的插件环境。

(1)在pom.xml里面拉Jar包:


		<dependency>
			<groupId>com.github.pagehelper</groupId>
			<artifactId>pagehelper-spring-boot-starter</artifactId>
			<version>${pagehelper-spring-boot.version}</version>
		</dependency>

(2)在application.properties配置里面设置:

pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql

(3)下面直接开始写数据层与逻辑层,实体类如下:

package com.demo.model;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

//商品表实体类;
public class Commodity {
	   public int cid;             //商品id;
	   public BigDecimal cprice;   //商品价格;
	   public String ccode;        //商品编码;
	   public int ctype;           //商品类型;
	   public String cname;        //商品名称;
	   public ComType tid;
	   public ComType tname;
	   public int countx;          //商品数量;
   public Commodity(Commodity g, int i) {
		// TODO Auto-generated constructor stub
	}
   public Commodity(){}
/*public Commodity(Map<String, Object> g, int i) {
	// TODO Auto-generated constructor stub
}*/
public Commodity(Commodity g) {
	// TODO Auto-generated constructor stub
}
public Commodity(Map<String, Commodity> g, int i) {
	// TODO Auto-generated constructor stub
}
public ComType getTid() {
		return tid;
	}

	public void setTid(ComType tid) {
		this.tid = tid;
	}

	public ComType getTname() {
		return tname;
	}

	public void setTname(ComType tname) {
		this.tname = tname;
	}

	public int getCountx() {
		return countx;
	}

	public void setCountx(int countx) {
		this.countx = countx;
	}

@Override
public String toString() {
	return "Commodity [cid=" + cid + ", cprice=" + cprice + ", ccode=" + ccode + ", ctype=" + ctype + ", cname=" + cname
			+ ", tid=" + tid + ", tname=" + tname + ", countx=" + countx + "]";
}

   public int getCid() {
	return cid;
}
public void setCid(int cid) {
	this.cid = cid;
}
public String getCname() {
	return cname;
}
public void setCname(String cname) {
	this.cname = cname;
}
public BigDecimal getCprice() {
	return cprice;
}
public void setCprice(BigDecimal cprice) {
	this.cprice = cprice;
}
public String getCcode() {
	return ccode;
}
public void setCcode(String ccode) {
	this.ccode = ccode;
}
public int getCtype() {
	return ctype;
}
public void setCtype(int ctype) {
	this.ctype = ctype;
}
}

(4)Dao层如下:

package com.demo.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;

import com.demo.model.Commodity;
import com.demo.utils.Page;

 @Mapper
public interface CommodityDao{
	 //主页展示商品查询;
   public List<Commodity> comSelect();
}

(5)Service层如下:

package com.demo.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


import com.demo.mapper.CommodityDao;
import com.demo.model.Commodity;
import com.demo.model.Result;
import com.demo.utils.Page;
@Service
public class CommodityService {
	@Resource
	private CommodityDao comm;
	/**
	 * 商品页面展示查询;
	 * @return
	 * @throws Exception
	 */
    public List<Commodity> comServiceSelect()throws Exception{
    	List<Commodity> list=comm.comSelect();
    	return list;
    }

}

(6)controller控制层也就是Action层如下:

package com.demo.controller;

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.demo.model.Commodity;
import com.demo.model.Login;
import com.demo.model.Order;
import com.demo.model.Result;
import com.demo.model.Sex;
import com.demo.service.CommodityService;
import com.demo.service.LoginService;
import com.demo.service.OrderService;
import com.demo.service.SexService;
import com.demo.utils.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Controller
@RequestMapping("/")
public class SpringBootUsersController {
	@Autowired
	private  CommodityService comm;

	
	@RequestMapping("/findCommodityAction_1")
	public String findCommodityAction_1(@RequestParam(defaultValue = "1",value = "pageNum")Integer pageNum,Integer pageSize,HttpServletRequest request,HttpServletResponse respoes)throws Exception{
		//分页插件;
        //这个里面是两个参数:pageNum(当前页数)与pageSize(每页要显示的数据数),这里直接给它们初始值为:pageNum=1,pageSize=4;
		PageHelper.startPage(pageNum,4);
		//获取数据;
		List<Commodity> list=comm.comServiceSelect();
        //然后把查询出来的数据放到插件自带的PageInfo对象里面;
		PageInfo<Commodity> pageInfo = new PageInfo<Commodity>(list);
		request.setAttribute("list",pageInfo);
		return "text";
	}

}

(7)sql.xml其实数据库sql语句跟平时一样没区别如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
   <mapper namespace="com.demo.mapper.CommodityDao">
    <resultMap type="com.demo.model.Commodity" id="comm">
     <id column="cid" property="cid"/>
     <result column="cname" property="cname"/>
     <result column="cprice" property="cprice"/>
     <result column="ccode" property="ccode"/>
     <result column="countx" property="countx"/>
      <association property="tname"  javaType="com.demo.model.ComType">
       <result column="tid" property="tid"/>
       <result column="tname" property="tname"/>
      </association>
    </resultMap>
    <select id="comSelectCount">
     SELECT count(*) totalpage
       FROM commodity
    </select>
    <!-- 首页商品展示查询 -->
    <select id="comSelect" resultMap="comm">
        SELECT 
              cid,
              cname,
              cprice,
              ccode,
              tname,
              countx
        FROM commodity 
        LEFT JOIN comtype ON commodity.ctype=comtype.tid
    </select>
  </mapper>

(8)视图层也就是页面如下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>

<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %> 
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'text.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
<script type="text/javascript" src="js/jquery-1.11.1.js"></script>
    <link rel="stylesheet" type="text/css" href="css/index.css"/>
    <link rel="stylesheet" href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css">  
    <script src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    
    <link rel="stylesheet" type="text/css" href="css/H-ui.admin.css"/>
    <link rel="stylesheet" type="text/css" href="css/H-ui.css"/>
    <link rel="stylesheet" type="text/css" href="css/H-ui.login.css"/>
    <link rel="stylesheet" type="text/css" href="css/H-ui.min.css"/>
    <link rel="stylesheet" type="text/css" href="css/style.css"/>
    
    <script type="text/javascript" src="js/H-ui.admin.js"></script>
    <script type="text/javascript" src="js/H-ui.js"></script>
    <script type="text/javascript" src="js/H-ui.min.js"></script>
    <style type="text/css">
     #max{
          width:1366px;
          height:600px; 
     }
     #ye{
          margin:0 auto;
          width:366px;
          height:70px; 
          /* border: 1px red solid; */
          text-align: center;
          line-height: 70px;
     }
    </style>
  </head>
  
  <body>
    <div id="max">
       <table class="table table-hover">
	<caption>商品分页展示</caption>
	<thead>
		<tr>
			<th>商品编号</th>
			<th>商品名称</th>
			<th>商品编码</th>
			<th>商品类型</th>
			<th>商品价格</th>
		</tr>
	</thead>
	<tbody id="tbooys">
	<c:forEach items="${list.list}" var="item">
		<tr>
			<td>${item.cid}</td>
			<td>${item.cname}</td>
			<td>${item.ccode}</td>
			<td>${item.tname.tname}</td>
			<td>${item.cprice}</td>
		</tr>
	</c:forEach>
	</tbody>
</table>
  <div id="ye">
    <p>当前第  ${list.pageNum} 页,总 ${list.pages} 页,共 ${list.total} 条记录</p>
       <p>
          <a href="${ctx}/findCommodityAction_1?pageNum=1">首页</a>
          <a href="${ctx}/findCommodityAction_1?pageNum=${list.prePage}">上一页</a>
          <a href="${ctx}/findCommodityAction_1?pageNum=${list.nextPage}">下一页</a>
          <a href="${ctx}/findCommodityAction_1?pageNum=${list.pages}">尾页</a>
       </p>
  </div>
</div>  
 </body>
</html>

(10)效果图如下:

as

# Spring Boot 集成 MyBatis, 分页插件 PageHelper, 通用 Mapper ## 项目依赖 ```xml <!--mybatis--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> <!--mapper--> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> <!--pagehelper--> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> ``` ## Spring DevTools 配置 在使用 DevTools 时,通用Mapper经常会出现 class x.x.A cannot be cast to x.x.A。 同一个类如果使用了不同的类加载器,就会产生这样的错误,所以解决方案就是让通用Mapper和实体类使用相同的类加载器即可。 DevTools 默认会对 IDE 中引入的所有项目使用 restart 类加载器,对于引入的 jar 包使用 base 类加载器,因此只要保证通用Mapper的jar包使用 restart 类加载器即可。 在 `src/main/resources` 中创建 META-INF 目录,在此目录下添加 spring-devtools.properties 配置,内容如下: ```properties restart.include.mapper=/mapper-[\\w-\\.]+jar restart.include.pagehelper=/pagehelper-[\\w-\\.]+jar ``` 使用这个配置后,就会使用 restart 类加载加载 include 进去的 jar 包。 ## 集成 MyBatis Generator 通过 Maven 插件集成的,所以运行插件使用下面的命令: >mvn mybatis-generator:generate Mybatis Geneator 详解: >http://blog.youkuaiyun.com/isea533/article/details/42102297 ## application.properties 配置 ```properties #mybatis mybatis.type-aliases-package=tk.mybatis.springboot.model mybatis.mapper-locations=classpath:mapper/*.xml #mapper #mappers 多个接口时逗号隔开 mapper.mappers=tk.mybatis.springboot.util.MyMapper mapper.not-empty=false mapper.identity=MYSQL #pagehelper pagehelper.helperDialect=mysql pagehelper.reasonable=true pagehelper.supportMethodsArguments=true pagehelper.params=count=countSql ``` ## application.yml 配置 完整配置可以参考 [src/main/resources/application-old.yml](https://github.com/abel533/MyBatis-Spring-Boot/blob/master/src/main/resources/application-old.yml) ,和 MyBatis 相关的部分配置如下: ```yaml mybatis: type-aliases-package: tk.mybatis.springboot.model mapper-locations: classpath:mapper/*.xml mapper: mappers: - tk.mybatis.springboot.util.MyMapper not-empty: false identity: MYSQL pagehelper: helperDialect: mysql reasonable: true supportMethodsArguments: true params: count=countSql ``` 注意 mapper 配置,因为参数名固定,所以接收参数使用的对象,按照 Spring Boot 配置规则,大写字母都变了带横线的小写字母。针对如 IDENTITY(对应i-d-e-n-t-i-t-y)提供了全小写的 identity 配置,如果 IDE 能自动提示,看自动提示即可。 ## SSM集成的基础项目 >https://github.com/abel533/Mybatis-Spring ## MyBatis工具 http://www.mybatis.tk - 推荐使用 Mybatis 通用 Mapper3 https://github.com/abel533/Mapper - 推荐使用 Mybatis 分页插件 PageHelper https://github.com/pagehelper/Mybatis-PageHelper ## 作者信息 - 作者博客:http://blog.youkuaiyun.com/isea533 - 作者邮箱:abel533@gmail.com
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值