一个简单的图书管理demo,基于 SSMP(Spring+SpringMVC+MyBatis-Plus)的CRUD (增删改查) 模块
案例实现方案分析
SSMP案例制作流程解析
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<scope>runtimescope>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.5.1version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druid-spring-boot-starterartifactId>
<version>1.2.8version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
dependencies>
tbl_book.sql
DROP TABLE IF EXISTS `tbl_book`;
CREATE TABLE `tbl_book` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`type` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`description` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 19 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of tbl_book
-- ----------------------------
INSERT INTO `tbl_book` VALUES (1, '计算机理论', 'Java编程思想(第4版)', 'Java学习经典,殿堂级著作!赢得了全球程序员的广泛赞誉。');
INSERT INTO `tbl_book` VALUES (2, '计算机理论', '计算机组成原理', '资深的计算机体系结构教育家Alan Clements博士编写,涵盖计算机系统的组成和体系结构的基本概念、指令系统以及处理器实现等涉及计算机组成原理课程的内容。');
INSERT INTO `tbl_book` VALUES (3, '程序设计', 'C++ Primer Plus 第6版 中文版', 'C++程序设计经典教程,畅销30年的C++大百科全书全新升级,经典C++入门教程十年新版再现');
INSERT INTO `tbl_book` VALUES (4, '程序设计', 'RocketMQ技术内幕:RocketMQ架构设计与实现原理(第2版)', '畅销书升级,RocketMQ创始人高度评价,深入源码分析技术架构和实现原理,打造高性能、高可用、高吞吐量、低延迟RocketMQ');
INSERT INTO `tbl_book` VALUES (5, '程序设计', ' 深入理解Java虚拟机:JVM高级特性与实践(第3版)', '周志明虚拟机新作,第3版新增内容近50%,5个维度全面剖析JVM,大厂面试知识点全覆盖。与 Java编程思想、Effective Java、Java核心技术 堪称:Java四大名著');
INSERT INTO `tbl_book` VALUES (6, '历史', '见识城邦·人类简史:从动物到上帝(新版)', '以色列新锐历史学家尤瓦尔·赫拉利代表作,第十届文津图书奖获奖作品');
INSERT INTO `tbl_book` VALUES (7, '历史', '中国通史', '吕思勉先生写给普通读者的中国通史入门书,用白话文写成的中国通史,把历史从“帝王的家谱”转变为人类的进化史');
INSERT INTO `tbl_book` VALUES (8, '哲学', '理想国(柏拉图代表作)', '奠定西方哲学史的源流之作。2021新译本,以斯灵斯校勘本为底本,遵照“字对字”的原则,从古希腊原文直译,兼顾准确性和语言通顺性,助你读懂理想国。');
INSERT INTO `tbl_book` VALUES (9, '哲学', '苏格拉底的申辩', '《柏拉图注疏集:苏格拉底的申辩》记述的是公元前399年,一个叫莫勒图斯的年轻人在雅典状告哲学家苏格拉底,说他不信城邦诸神,引进新的精灵之事,败坏青年。 于是,苏格拉底被传讯,在500人组成的陪审团面前作了著名的申辩。');
INSERT INTO `tbl_book` VALUES (10, '文学', '鲁迅全集', '大师全集,完整收录,鲁迅毕生之心血尽归于此。\r\n\r\n 鲁迅是中国20世纪的文学家、思想家、革命家,中国近代文学巨匠。他早年留学于日本,后来弃医从文,他用笔耕不辍的文字为新一代青年们指引方向,在国内外思想文化领域有着极高的声誉。');
INSERT INTO `tbl_book` VALUES (11, '文学', '人间清醒', '茅盾文学奖获得者梁晓声2021全新力作');
INSERT INTO `tbl_book` VALUES (12, '经济', '八次危机:中国的真实经验1949-2009', '著名“三农”专家温铁军,用经济的独特视角,重新审视中国的1949-2009,历史给我了我们怎样的真实经验?');
SET FOREIGN_KEY_CHECKS = 1;
application.yml
# 设置端口为80方便访问
server:
port: 80
小结
lombok
,一个Java类库,提供了一组注解,简化POJO实体类开发
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
dependency>
lombok
版本由 SpringBoot 提供,无需指定版本
@Data
@Data
public class Book {
private Integer id;
private String type;
private String name;
private String description;
}
get/set方法
、toString方法
、hashCode方法
、equals方法
等小结
CRUD
)
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.5.1version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druid-spring-boot-starterartifactId>
<version>1.2.8version>
dependency>
自增
策略)# druid 数据源配置
spring:
datasource:
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC
username: root
password: 283619
# mybatis-plus 配置
mybatis-plus:
global-config:
db-config:
table-prefix: tbl_
id-type: auto # 主键自增策略
@Mapper
public interface BookDao extends BaseMapper<Book> {
}
@SpringBootTest
public class BookDaoTestCase {
@Autowired
private BookDao bookDao;
// 根据id查询单个数据
@Test
void testGetById() {
System.out.println(bookDao.selectById(1));
}
// 新增数据
@Test
void testSave() {
Book book = new Book();
book.setType("测试用例-小说");
book.setName("测试用例-狂人日记");
book.setDescription("鲁迅");
bookDao.insert(book);
}
// 更新操作
@Test
void testUpdate() {
Book book = new Book();
book.setId(13);
book.setType("测试用例-小说");
book.setName("测试用例-狂人日记");
book.setDescription("鲁迅-新文化运动");
bookDao.updateById(book);
}
// 删除操作
@Test
void testDelete() {
bookDao.deleteById(19);
}
// 查询全部数据
@Test
void testGetAll() {
List<Book> list = bookDao.selectList(null);
for (Book book : list) {
System.out.println(book);
}
}
}
小结
MyBatis-Plus
的日志标准输出
# mybatis-plus 配置
mybatis-plus:
global-config:
db-config:
table-prefix: tbl_
id-type: auto # 主键自增策略
configuration:
# 开启MyBatisPlus的日志
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 标准输出
// 分页操作
@Test
void testGetPage() {
IPage page = new Page(1, 5);
bookDao.selectPage(page, null);
}
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
// 1. 定义 Mybatis-Plus 拦截器
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 2. 添加具体的拦截器(分页拦截器)
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}
}
// 分页操作
@Test
void testGetPage() {
IPage page = new Page(2, 5);
bookDao.selectPage(page, null);
System.out.println("获取当前页:" + page.getCurrent());
System.out.println("获取每页显示个数:" + page.getSize());
System.out.println("获取总个数:" + page.getTotal());
System.out.println("获取总页数:" + page.getPages());
// 获取分页查询数据
System.out.println("获取分页查询数据:");
List<Book> books = page.getRecords();
for (Book book : books) {
System.out.println(book);
}
}
小结
写法一
// 根据条件进行查询
@Test
void testGetBy() {
QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
// 查询包含"java"名称的书籍有哪些
queryWrapper.like("name", "java");
bookDao.selectList(queryWrapper);
}
写法二(推荐)
QueryWrapper
对象封装查询条件,推荐使用 LambdaQueryWrapper
对象,所有查询操作封装成方法调用 // 根据条件进行查询
@Test
void testGetBy2() {
LambdaQueryWrapper<Book> queryWrapper = new LambdaQueryWrapper<>();
// 查询包含"java"名称的书籍有哪些
queryWrapper.like(Book::getName, "java");
bookDao.selectList(queryWrapper);
}
支持动态拼写查询条件(
业务开发一般是这种写法
)
// 根据条件进行查询
@Test
void testGetBy3() {
String name = null;
LambdaQueryWrapper<Book> queryWrapper = new LambdaQueryWrapper<>();
// 如果name为空,就不进行查询
queryWrapper.like(name != null, Book::getName, name);
bookDao.selectList(queryWrapper);
}
// 根据条件进行查询
@Test
void testGetBy3() {
String name = "中国";
LambdaQueryWrapper<Book> queryWrapper = new LambdaQueryWrapper<>();
// 查询包含"中国"名称的书籍有哪些
// 如果name为空,就不进行查询
queryWrapper.like(name != null, Book::getName, name);
bookDao.selectList(queryWrapper);
}
小结
CRUD
)selectByUserNameAndPassword(String username,String password);
数据层接口login(String username,String password);
Service层接口接口定义
public interface BookService {
Boolean save(Book book);
Boolean update(Book book);
Boolean delete(Integer id);
Book getById(Integer id);
List<Book> getAll();
// currentPage:当前页码值
// pageSize:每页显示个数
IPage<Book> getPage(int currentPage, int pageSize);
}
实现类定义
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookDao bookDao;
@Override
public Boolean save(Book book) {
// 当插入成功,返回的是影响行计数,大于0表示插入成功,否则插入失败
return bookDao.insert(book) > 0;
}
@Override
public Boolean update(Book book) {
return bookDao.updateById(book) > 0;
}
@Override
public Boolean delete(Integer id) {
return bookDao.deleteById(id) > 0;
}
@Override
public Book getById(Integer id) {
return bookDao.selectById(id);
}
@Override
public List<Book> getAll() {
return bookDao.selectList(null);
}
// currentPage:当前页码值
// pageSize:每页显示个数
public IPage<Book> getPage(int currentPage, int pageSize) {
IPage page = new Page(currentPage, pageSize);
bookDao.selectPage(page, null);
return page;
}
}
测试类定义
@SpringBootTest
public class BookServiceTestCase {
@Autowired
private BookService bookService;
@Test
void testGetById() {
System.out.println(bookService.getById(4));
}
@Test
void testSave() {
Book book = new Book();
book.setType("测试用例-小说");
book.setName("测试用例-狂人日记");
book.setDescription("鲁迅");
bookService.save(book);
}
@Test
void testUpdate() {
Book book = new Book();
book.setId(20);
book.setType("测试用例-小说");
book.setName("测试用例-狂人日记");
book.setDescription("鲁迅-新文化运动");
bookService.update(book);
}
@Test
void testDelete() {
bookService.delete(20);
}
@Test
void testGetAll() {
System.out.println(bookService.getAll());
}
@Test
void testGetPage() {
IPage<Book> page = bookService.getPage(2, 5);
System.out.println("获取当前页:" + page.getCurrent());
System.out.println("获取每页显示个数:" + page.getSize());
System.out.println("获取总个数:" + page.getTotal());
System.out.println("获取总页数:" + page.getPages());
// 获取分页查询数据
System.out.println("获取分页查询数据:");
List<Book> books = page.getRecords();
for (Book book : books) {
System.out.println(book);
}
}
}
小结
快速开发方案
ISerivce
)与业务层通用实现类(ServiceImpl
)接口定义
public interface IBookService extends IService<Book> {
}
/**
* @author xiexu
* @create 2022-04-06 13:54
*/
public interface IBookService extends IService<Book> {
// 注意:追加的操作与原始操作通过名称区分,功能类似
// 新增
Boolean saveBook(Book book);
// 删除
Boolean delete(Integer id);
// 修改
Boolean modify(Book book);
// 根据id获取数据
Book get(Integer id);
// 分页查询
IPage<Book> getPage(int currentPage, int pageSize);
}
实现类定义
@Service
public class BookServiceImpl extends ServiceImpl<BookDao, Book> implements IBookService {
}
/**
* @author xiexu
* @create 2022-04-06 13:58
*/
@Service
public class BookServiceImpl extends ServiceImpl<BookDao, Book> implements IBookService {
@Autowired
private BookDao bookDao;
@Override
public Boolean saveBook(Book book) {
return bookDao.insert(book) > 0;
}
@Override
public Boolean delete(Integer id) {
return bookDao.deleteById(id) > 0;
}
@Override
public Boolean modify(Book book) {
return bookDao.updateById(book) > 0;
}
@Override
public Book get(Integer id) {
return bookDao.selectById(id);
}
@Override
public IPage<Book> getPage(int currentPage, int pageSize) {
IPage page = new Page(currentPage, pageSize);
bookDao.selectPage(page, null);
return page;
}
}
测试类定义
@SpringBootTest
public class BookServiceTest {
@Autowired
private IBookService bookService;
@Test
void testGetById() {
System.out.println(bookService.getById(4));
}
@Test
void testSave() {
Book book = new Book();
book.setType("测试用例-小说");
book.setName("测试用例-狂人日记");
book.setDescription("鲁迅");
bookService.save(book);
}
@Test
void testUpdate() {
Book book = new Book();
book.setId(21);
book.setType("测试用例-小说");
book.setName("测试用例-狂人日记");
book.setDescription("鲁迅-新文化运动");
bookService.updateById(book);
}
@Test
void testDelete() {
bookService.removeById(21);
}
@Test
void testGetAll() {
System.out.println(bookService.list());
}
@Test
void testGetPage() {
IPage<Book> page = new Page<>(2, 5);
bookService.page(page);
System.out.println("获取当前页:" + page.getCurrent());
System.out.println("获取每页显示个数:" + page.getSize());
System.out.println("获取总个数:" + page.getTotal());
System.out.println("获取总页数:" + page.getPages());
// 获取分页查询数据
System.out.println("获取分页查询数据:");
List<Book> books = page.getRecords();
for (Book book : books) {
System.out.println(book);
}
}
}
小结
不要覆盖原始操作
,避免原始提供的功能丢失
表现层开发
/**
* @author xiexu
* @create 2022-04-07 10:09
*/
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private IBookService bookService;
@GetMapping
public List<Book> getAll() {
return bookService.list();
}
@PostMapping
public Boolean save(@RequestBody Book book) {
return bookService.save(book);
}
@PutMapping
public Boolean update(@RequestBody Book book) {
return bookService.updateById(book);
}
@DeleteMapping("/{id}")
public Boolean delete(@PathVariable Integer id) {
return bookService.delete(id);
}
@GetMapping("/{id}")
public Book getById(@PathVariable Integer id) {
return bookService.getById(id);
}
@GetMapping("/{currentPage}/{pageSize}")
public IPage<Book> getPage(@PathVariable int currentPage, @PathVariable int pageSize) {
return bookService.getPage(currentPage, pageSize);
}
}
Postman
进行功能测试小结
之前的格式
增加一个 data 属性,把数据全部封装到 data 里
增加 一个状态属性
/**
* @author xiexu
* @create 2022-04-07 11:22
*/
@Data
public class R {
private Boolean flag;
private Object data;
public R() {
}
/**
* 不返回数据的构造方法
*
* @param flag
*/
public R(Boolean flag) {
this.flag = flag;
}
/**
* 返回数据的构造方法
*
* @param flag
* @param data
*/
public R(Boolean flag, Object data) {
this.flag = flag;
this.data = data;
}
}
/**
* @author xiexu
* @create 2022-04-07 10:09
*/
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private IBookService bookService;
@GetMapping
public R getAll() {
return new R(true, bookService.list());
}
@PostMapping
public R save(@RequestBody Book book) {
return new R(bookService.save(book));
}
@PutMapping
public R update(@RequestBody Book book) {
return new R(bookService.updateById(book));
}
@DeleteMapping("/{id}")
public R delete(@PathVariable Integer id) {
return new R(bookService.delete(id));
}
@GetMapping("/{id}")
public R getById(@PathVariable Integer id) {
return new R(true, bookService.getById(id));
}
@GetMapping("/{currentPage}/{pageSize}")
public R getPage(@PathVariable int currentPage, @PathVariable int pageSize) {
return new R(true, bookService.getPage(currentPage, pageSize));
}
}
Postman
进行功能测试小结
将提前编辑好的静态资源文件放入 resource/static
目录中,执行maven插件中的clean
脚本清除 target 中的项目缓存。
打开浏览器访问 localhost/pages/books.html
小结
axios
发送异步请求books.html
中修改对应位置的代码,执行完毕后可以看到浏览器控制台和IDEA控制台有数据信息显示。 //钩子函数,VUE对象初始化完成后自动执行
created() {
// 调用查询全部数据的操作
this.getAll();
},
methods: {
//列表
getAll() {
// 发送异步请求
axios.get("/books").then((res) => {
console.log(res.data);
});
},
小结
resources/static
目录下created
钩子函数用于初始化页面时发起调用axios
发送异步请求获取数据后确认前后端是否联通列表页
//列表
getAll() {
// 发送异步请求
axios.get("/books").then((res) => {
// console.log(res.data);
this.dataList = res.data.data; // res.data是前端返回给后端的数据名
});
},
小结
// 弹出添加窗口
handleCreate() {
this.dialogFormVisible = true;
this.resetForm();
},
// 重置表单
resetForm() {
this.formData = {};
},
// 弹出添加窗口
handleCreate() {
this.dialogFormVisible = true;
this.resetForm();
},
// 添加
handleAdd() {
// 发送异步请求
axios.post("/books", this.formData).then((res) => {
// 判断当前操作是否成功
if (res.data.flag) {
// 1.关闭弹层
this.dialogFormVisible = false;
this.$message.success("添加成功");
} else {
this.$message.error("添加失败");
}
}).finally(() => {
// 2.重新加载数据
this.getAll();
});
},
// 取消
cancel() {
// 1.关闭弹层
this.dialogFormVisible = false;
// 2.提示用户
this.$message.info("当前操作取消");
},
小结
// 发送异步请求
axios.delete("/books/" + row.id).then((res) => {
// 判断当前操作是否成功
if (res.data.flag) { // res.data是前端返回给后端的数据名
this.$message.success("删除成功");
} else {
this.$message.error("删除失败");
}
}).finally(() => {
// 删除后需要重新加载数据
this.getAll();
});
// 删除
handleDelete(row) {
// 1.删除弹出框
this.$confirm("此操作将永久删除当前信息,是否继续?", "提示", {type: "info"}).then(() => {
// 2.发送异步请求
axios.delete("/books/" + row.id).then((res) => {
// 判断当前操作是否成功
if (res.data.flag) { // res.data是前端返回给后端的数据名
this.$message.success("删除成功");
} else {
this.$message.error("删除失败");
}
}).finally(() => {
// 删除后需要重新加载数据
this.getAll();
});
}).catch(() => {
// 3.取消删除操作
this.$message.info("取消操作");
});
},
小结
//弹出编辑窗口
handleUpdate(row) {
// 发送异步请求
axios.get("/books/" + row.id).then((res) => {
if (res.data.flag && res.data.data != null) {
// 展示弹层,加载数据
this.dialogFormVisible4Edit = true;
this.formData = res.data.data;
} else {
this.$message.error("数据同步失败,自动刷新");
}
}).finally(() => {
// 重新加载数据
this.getAll();
});
},
// 删除
handleDelete(row) {
// 1.删除弹出框
this.$confirm("此操作将永久删除当前信息,是否继续?", "提示", {type: "info"}).then(() => {
// 2.发送异步请求
axios.delete("/books/" + row.id).then((res) => {
// 判断当前操作是否成功
if (res.data.flag) { // res.data是前端返回给后端的数据名
this.$message.success("删除成功");
} else {
this.$message.error("数据同步失败,自动刷新");
}
}).finally(() => {
// 删除后需要重新加载数据
this.getAll();
});
}).catch(() => {
// 3.取消删除操作
this.$message.info("取消操作");
});
},
小结
//修改
handleEdit() {
// 发送异步请求
axios.put("/books", this.formData).then((res) => {
// 判断当前操作是否成功
if (res.data.flag) {
// 1.关闭弹层
this.dialogFormVisible4Edit = false;
this.$message.success("修改成功");
} else {
this.$message.error("修改失败");
}
}).finally(() => {
// 2.重新加载数据
this.getAll();
});
},
//取消
cancel() {
// 1.关闭弹层
this.dialogFormVisible = false;
this.dialogFormVisible4Edit = false;
// 2.提示用户
this.$message.info("当前操作取消");
},
小结
// 作为springmvc的异常处理器
@RestControllerAdvice
public class ProjectExceptionAdvice {
// 拦截所有的异常信息
@ExceptionHandler
public R doException(Exception ex) {
// 记录日志
// 通知运维
// 通知开发
ex.printStackTrace();
return new R(false, "服务器故障,请稍后再试!");
}
}
@Data
public class R {
private Boolean flag;
private Object data;
private String msg;
public R() {
}
/**
* 不返回数据的构造方法
*
* @param flag
*/
public R(Boolean flag) {
this.flag = flag;
}
/**
* 返回数据的构造方法
*
* @param flag
* @param data
*/
public R(Boolean flag, Object data) {
this.flag = flag;
this.data = data;
}
/**
* 返回异常信息的构造方法
*
* @param flag
* @param msg
*/
public R(Boolean flag, String msg) {
this.flag = flag;
this.msg = msg;
}
}
//添加
handleAdd() {
// 发送异步请求
axios.post("/books", this.formData).then((res) => {
// 判断当前操作是否成功
if (res.data.flag) {
// 1.关闭弹层
this.dialogFormVisible = false;
this.$message.success("添加成功");
} else {
this.$message.error(res.data.msg);
}
}).finally(() => {
// 2.重新加载数据
this.getAll();
});
},
@PostMapping
public R save(@RequestBody Book book) throws Exception {
if (book.getName().equals("123")) {
throw new Exception();
}
boolean flag = bookService.save(book);
return new R(flag, flag ? "添加成功^_^" : "添加失败-_-!");
}
//添加
handleAdd() {
// 发送异步请求
axios.post("/books", this.formData).then((res) => {
// 判断当前操作是否成功
if (res.data.flag) {
// 1.关闭弹层
this.dialogFormVisible = false;
this.$message.success(res.data.msg);
} else {
this.$message.error(res.data.msg);
}
}).finally(() => {
// 2.重新加载数据
this.getAll();
});
},
小结
data: {
pagination: { // 分页相关模型数据
currentPage: 1, // 当前页码
pageSize: 10, // 每页显示的记录数
total: 0, // 总记录数
}
},
getAll() {
axios.get("/books/" + this.pagination.currentPage + "/" + this.pagination.pageSize).then((res) => {
});
},
@GetMapping("/{currentPage}/{pageSize}")
public R getPage(@PathVariable int currentPage, @PathVariable int pageSize) {
return new R(true, bookService.getPage(currentPage, pageSize));
}
//分页查询
getAll() {
// 发送异步请求
axios.get("/books/" + this.pagination.currentPage + "/" + this.pagination.pageSize).then((res) => {
this.pagination.pageSize = res.data.data.size;
this.pagination.currentPage = res.data.data.current;
this.pagination.total = res.data.data.total;
this.dataList = res.data.data.records;
});
},
//切换页码
handleCurrentChange(currentPage) {
//修改页码值为当前选中的页码值
this.pagination.currentPage = currentPage;
//执行查询
this.getAll();
},
小结
@GetMapping("/{currentPage}/{pageSize}")
public R getPage(@PathVariable int currentPage, @PathVariable int pageSize) {
IPage<Book> page = bookService.getPage(currentPage, pageSize);
// 如果当前页码值大于总页码值,那么重新执行查询操作时,使用最大页码值作为当前页码值
if (currentPage > page.getPages()) {
page = bookService.getPage((int) page.getPages(), pageSize);
}
return new R(true, page);
}
小结
pagination: {//分页相关模型数据
currentPage: 1,//当前页码
pageSize: 10,//每页显示的记录数
total: 0,//总记录数
type: "",
name: "",
description: ""
}
查询
新建
//分页查询
getAll() {
// 组织参数,拼接url请求地址
param = "?type=" + this.pagination.type;
param += "&name=" + this.pagination.name;
param += "&description=" + this.pagination.description;
// console.log(param);
// 发送异步请求
axios.get("/books/" + this.pagination.currentPage + "/" + this.pagination.pageSize + param).then((res) => {
this.pagination.pageSize = res.data.data.size;
this.pagination.currentPage = res.data.data.current;
this.pagination.total = res.data.data.total;
this.dataList = res.data.data.records;
});
},
@GetMapping("/{currentPage}/{pageSize}")
public R getPage(@PathVariable int currentPage, @PathVariable int pageSize, Book book) {
System.out.println("参数====>" + book);
IPage<Book> page = bookService.getPage(currentPage, pageSize);
// 如果当前页码值大于总页码值,那么重新执行查询操作时,使用最大页码值作为当前页码值
if (currentPage > page.getPages()) {
page = bookService.getPage((int) page.getPages(), pageSize);
}
return new R(true, page);
}
// 分页的条件查询
IPage<Book> getPage(int currentPage, int pageSize, Book book);
@Override
public IPage<Book> getPage(int currentPage, int pageSize, Book book) {
LambdaQueryWrapper<Book> lqw = new LambdaQueryWrapper();
lqw.like(Strings.isNotEmpty(book.getType()), Book::getType, book.getType());
lqw.like(Strings.isNotEmpty(book.getName()), Book::getName, book.getName());
lqw.like(Strings.isNotEmpty(book.getDescription()), Book::getDescription, book.getDescription());
IPage page = new Page(currentPage, pageSize);
bookDao.selectPage(page, lqw);
return page;
}
@GetMapping("/{currentPage}/{pageSize}")
public R getPage(@PathVariable int currentPage, @PathVariable int pageSize, Book book) {
// System.out.println("参数====>" + book);
IPage<Book> page = bookService.getPage(currentPage, pageSize, book);
// 如果当前页码值大于总页码值,那么重新执行查询操作时,使用最大页码值作为当前页码值
if (currentPage > page.getPages()) {
page = bookService.getPage((int) page.getPages(), pageSize, book);
}
return new R(true, page);
}
小结