Springboot整合Thymeleaf+Mybatis-分页查询
分页查询分两种:
1. 不带条件查询,并分页展示!
1. 带条件查询,并查询时,按条件查询的数据展示!
1、初始MyBatis 3的动态SQL
在学习分页之前,我们需要对 Mybatis的动态SQL有一定的了解!在做条件查询时,就会用到动态SQL!
- 动态 SQL 是 MyBatis 的强大特性之一。
- 如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。
- 现在的MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。
MyBatis中的动态SQL元素(属性):
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
这里我提供一个链接供大家学习和使用:https://mybatis.org/mybatis-3/zh/dynamic-sql.html
2、分页查询
2.1 创建项目
- 创建Spring项目
2. 添加依赖和选择Springboot版本
2.2 导入Pagehelper jar包,依赖
<!--分页插件pagehelper-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.1</version>
</dependency>
<!--mybatis 的依赖jar报-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.3.0</version>
</dependency>
2.3 编写application.yml配置文件
# 服务器端口
server:
port: 8080
# spring配置
spring:
datasource: # 数据源
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/t149?characterEncoding=utf-8&serverTimezone=GMT+8
username: root
password: root
# thymeleaf配置
thymeleaf:
cache: false #缓存
mode: HTML #模板
encoding: UTF-8 #编码格式
prefix: classpath:/templates/ #前缀
suffix: .html #后缀
servlet:
content-type: text/html # servlet文本类型
# mybatis配置
mybatis:
mapper-locations: classpath:/com/ithjc/mapper/*.xml #mapper的xml映射文件
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #打印日志文件 分等级的
type-aliases-package: com.ithjc.pojo #实体类的别名
#重点:pagehelper配置-分页插件
pagehelper:
helper-dialect: mysql #数据库
reasonable: true
support-methods-arguments: true
params: count=countSql
2.4 数据库
-- 创建订单表 order
CREATE TABLE `order` (
`action_id` mediumint NOT NULL AUTO_INCREMENT COMMENT '操作id',
`order_sn` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '订单编号',
`action_user` mediumint NOT NULL COMMENT '操作人',
`order_status` tinyint(1) NULL DEFAULT NULL COMMENT '订单状态',
`pay_status` tinyint(1) NULL DEFAULT NULL COMMENT '支付状态',
`shipping_status` tinyint(1) NULL DEFAULT NULL COMMENT '配送状态',
`action_note` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '操作记录',
`action_time` datetime NULL DEFAULT NULL COMMENT '操作时间',
`status_desc` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '状态描述',
PRIMARY KEY (`action_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
-- 给添加数据
INSERT INTO `order` VALUES (1, '1001', 1, 1, 1, 0, '1', '2022-12-14 12:19:56', '正在配送');
INSERT INTO `order` VALUES (2, '1002', 1, 1, 1, 0, '1', '2022-12-14 12:19:56', '正在配送');
INSERT INTO `order` VALUES (3, '1003', 1, 1, 1, 1, '1', '2022-12-14 12:19:56', '正在配送');
INSERT INTO `order` VALUES (4, '1004', 1, 1, 1, 0, '1', '2022-12-14 12:19:56', '正在配送');
INSERT INTO `order` VALUES (5, '1005', 1, 1, 1, 0, '1', '2022-12-14 12:19:56', '正在配送');
2.5 pojo、mapper、service.impl、controller代码编写
2.5.1 pojo实体层
再 pom.xml中导入 lombak 的jar包依赖,即可使用@Data等注解!!已导入,可忽略!
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
@Data // 提供get、set方法 - 用于简化代码
@NoArgsConstructor //无参
@AllArgsConstructor //有参
public class Order {
private long actionId;
private String orderSn;
private long actionUser;
private long orderStatus;
private long payStatus;
private long shippingStatus;
private String actionNote;
private Date actionTime;
private String statusDesc;
}
2.5.2 mapper层
记得加入 @Mapper注解
@Mapper
public interface OrderMapper {
/**
* 不带条件 - 分页查询所有
* @return
*/
List<Order> findAll();
/**
* 带条件 - 分页查询所应聘
* @param orderSn
* @param orderStatus
* @return
*/
List<Order> findByOrderSnAndOrderStatus(String orderSn,String orderStatus);
}
2.5.3 mapper接口对应的 .xml文件 - OrderMapper.xml
<?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接口 -->
<mapper namespace="com.ithjc.mapper.OrderMapper">
<select id="findAll" resultType="Order">
select *
from `order`
</select>
<select id="findByOrderSnAndOrderStatus" parameterType="order" resultType="order">
select *
from `order`
<where>
1 = 1
<if test="orderSn != null and orderSn != ''">
and order_sn=#{orderSn}
</if>
<if test="orderStatus != null and orderStatus != ''">
and order_status=#{orderStatus}
</if>
</where>
</select>
</mapper>
2.5.4 service层
public interface OrderService {
// 不带条件 - 分页查询
PageInfo<Order> findAll(Integer pageIndex,Integer pageSize);
// 带条件 - 分页查询
PageInfo<Order> findByOrderSnAndOrderStatus(Integer pageIndex,Integer pageSize,String orderSn,String orderStatus);
}
2.5.5 service下的 impl层
记得加入@Service 注解
@Service
public class OrderServiceImpl implements OrderService {
@Autowired
private OrderMapper orderMapper;
@Override
public PageInfo<Order> findAll(Integer pageIndex,Integer pageSize) {
PageHelper.startPage(pageIndex,pageSize);
List<Order> all = orderMapper.findAll();
PageInfo<Order> orderPageInfo = new PageInfo<>(all);
return orderPageInfo;
}
@Override
public PageInfo<Order> findByOrderSnAndOrderStatus(Integer pageIndex,Integer pageSize,String orderSn, String orderStatus) {
PageHelper.startPage(pageIndex,pageSize);
List<Order> byOrderSnAndOrderStatus = orderMapper.findByOrderSnAndOrderStatus(orderSn, orderStatus);
PageInfo<Order> pageInfo = new PageInfo<>(byOrderSnAndOrderStatus);
return pageInfo ;
}
}
2.5.6 controller层
记得加入 @Controller 注解
@Controller
public class OrderController {
//@Autowired
//private ActionService actionService;
@Autowired
private OrderService orderService;
//http://localhost:8080/getPage
@RequestMapping("/getPage")
public String getAll(Model model,
@RequestParam(value = "pageIndex", required = false, defaultValue = "1") Integer pageIndex,
@RequestParam(value = "pageSize", required = false, defaultValue = "3") Integer pageSize) {
PageInfo<Order> all = orderService.findAll(pageIndex, pageSize);
model.addAttribute("page", all);
model.addAttribute("path", "/getPage?pageIndex=");
return "index";
}
//http://localhost:8080/getPageBy?orderSn=1001 -- 添加根据需求编写
@RequestMapping("/getPageBy")
public String getPageBy(Model model,
@RequestParam(value = "orderSn", required = false) String orderSn,
@RequestParam(value = "orderStatus", required = false) String orderStatus,
@RequestParam(value = "pageIndex", required = false, defaultValue = "1") Integer pageIndex,
@RequestParam(value = "pageSize", required = false, defaultValue = "3") Integer pageSize) {
PageInfo<Order> orderPageInfo = orderService.findByOrderSnAndOrderStatus(pageIndex, pageSize, orderSn, orderStatus);
model.addAttribute("page", orderPageInfo);
model.addAttribute("path", "/getPageBy?pageIndex=");
return "index";
}
}
2.5.7 tempplates 引擎模板,编写页面
这里只提供了,分页查询 - 注意:没有增删改!!!
index.html页面实现 - 其中提供page.html分页模板
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<br>
<br/>
<form th:action="@{/getPageBy}" style="text-align: center;margin: auto;">
订单编号:<input type="text" name="orderSn" style="width: 100px">
订单状态:<input type="text" name="orderStatus" style="width: 100px">
<input type="submit" value="查询">
</form>
<div>
<br>
<table border="1" style="text-align: center;margin: auto;">
<tr>
<th>id</th>
<th>编号</th>
<th>操作人</th>
<th>订单状态</th>
<th>支付状态</th>
<th>配送状态</th>
<th>操作记录</th>
<th>操作时间</th>
<th>状态描述</th>
<th>操作</th>
</tr>
<tr th:each="order : ${page.list}">
<td th:text="${order.actionId}"></td>
<td th:text="${order.orderSn}"></td>
<td th:text="${order.actionUser}"></td>
<td th:text="${order.orderStatus}"></td>
<td th:text="${order.payStatus}"></td>
<td th:text="${order.shippingStatus}"></td>
<td th:text="${order.actionNote}"></td>
<td th:text="${#dates.format(order.actionTime,'yyyy-MM-dd')}"></td>
<td th:text="${order.statusDesc}"></td>
<td>
<a href="">删除</a>
<a href="">编辑</a>
</td>
</tr>
</table>
</div>
<div style="text-align: center;margin: auto;">
<a href="">添加</a>
</div>
<!--引入page.html分页模板-->
<div th:insert="page::page"></div>
</body>
</html>
page.html分页模板
<!DOCTYPE html>
<!--suppress ALL--> <!-- 去掉红色下划线-->
<html>
<div th:fragment="page">
<style>
.page{
border: 1px solid blue;
margin-right: 5px;
padding: 3px 5px;
}
.page.active{
color: red;
border: 1px solid red;
}
</style>
<div style="float: left">
当前第<span th:text="${page.pageNum}"></span>页
总记录数<span th:text="${page.total}"></span>
</div>
<div style="float: right">
<a th:text="首页" th:if="${page.pageNum>1}" th:href="@{${path}}"></a>
<a th:text="上一页" th:if="${page.pageNum>1}" th:href="@{${path}+${page.pageNum-1}}"></a>
<a th:href="@{${path}+${i}}" th:each="i:${#numbers.sequence(1,page.pages)}" th:text="${i}"
th:class="${page.pageNum==i}? 'page active':'page'"></a>
<a th:text="下一页" th:if="${page.pageNum<page.pages}" th:href="@{${path}+${page.pageNum+1}}"></a>
<a th:text="尾页" th:if="${page.pageNum<page.pages}" th:href="@{${path}+${page.pages}}"></a>
</div>
</div>
</html>
3.测试接口 和 页面
3.1 直接进入页面
http://localhost:8080/getPage
3.2 输入参数,可以直接到达第2页面,并显示“首页”和“上一页”
http://localhost:8080/getPage?pageIndex=2
3.3 待条件的分页查询
3.3.1 直接到查询页面,再输入条件
http://localhost:8080/getPageBy
3.3.2 输入参数后,直接查询出,满足添加的分页数据