完整代码网盘链接:
链接:https://pan.baidu.com/s/1vKdsR-80C6t9yM7KXoX97g
提取码:xasl
该案例简单实现数据的CRUD以及分页功能。
org.projectlombok
lombok
true
1.18.4
package com.example.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Book {
private int id;
private String type;
private String name;
private String description;
}
com.baomidou
mybatis-plus-boot-starter
3.4.2
com.alibaba
druid-spring-boot-starter
1.2.6
server:
port: 80
#datasource
spring:
datasource:
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC
username: root
password: root
mybatis-plus:
global-config:
db-config:
#table??
table-prefix: tab_
#id??
id-type: auto
package com.example.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.domain.Book;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface BookDao extends BaseMapper {
}
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
package com.example.config;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
@Component
public class MPConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor mpInterceptor = new MybatisPlusInterceptor();
mpInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return mpInterceptor;
}
}
package com.example.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.domain.Book;
import org.springframework.stereotype.Service;
public interface IBookService extends IService {
IPage getPage(Integer currentPage, Integer pageSize);
IPage getPage(Integer currentPage, Integer pageSize, Book book);
}
package com.example.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dao.BookDao;
import com.example.domain.Book;
import com.example.service.IBookService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class BookServiceImpl extends ServiceImpl implements IBookService {
@Autowired
private BookDao bookDao;
@Override
public IPage getPage(Integer currentPage, Integer pageSize) {
IPage page = new Page<>(currentPage, pageSize);
IPage bookIPage = bookDao.selectPage(page, null);
return bookIPage;
}
@Override
public IPage getPage(Integer currentPage, Integer pageSize, Book book) {
IPage page = new Page<>(currentPage, pageSize);
LambdaQueryWrapper 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());
return bookDao.selectPage(page, lqw);
}
}
package com.example.controller.utils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.swing.text.StyledEditorKit;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class R {
private Boolean flag;
private Object data;
private String message;
public R(Boolean flag){
this.flag = flag;
}
public R(Boolean flag, String message){
this.flag = flag;
this.message = message;
}
public R(Boolean flag, Object data){
this.flag = flag;
this.data = data;
}
public R(String message){
this.flag = false;
this.message = message;
}
}
控制层具体代码如下
package com.example.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.controller.utils.R;
import com.example.domain.Book;
import com.example.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private IBookService iBookService;
@GetMapping
public R getAll(){
return new R(true, iBookService.list());
}
@PostMapping
public R save(@RequestBody Book book){
boolean flag = iBookService.save(book);
return new R(flag, flag ? "添加成功^_^" : "添加失败-_-!");
}
@DeleteMapping("{id}")
public R delete(@PathVariable Integer id){
return new R(iBookService.removeById(id));
}
@PutMapping
public R update(@RequestBody Book book){
return new R(iBookService.updateById(book));
}
@GetMapping("{id}")
public R getById(@PathVariable Integer id){
return new R(true, iBookService.getById(id));
}
@GetMapping("/{currentPage}/{pageSize}")
public R getPage(@PathVariable Integer currentPage, @PathVariable Integer pageSize, Book book){
IPage page = iBookService.getPage(currentPage, pageSize, book);
if (currentPage > page.getPages()){
page = iBookService.getPage((int)page.getPages(), pageSize);
}
return new R(null != page, page);
}
}
在pagination中加入模糊查询的三个参数
pagination: {//分页相关模型数据
currentPage: 1,//当前页码
pageSize:5,//每页显示的记录数
total:0,//总记录数
name: "",
type: "",
description: ""
}
将三个参数拼接
//分页查询
getAll() {
//1.获取查询条件,拼接查询条件
param = "?name=" + this.pagination.name;
param+= "&type="+this.pagination.type;
param+= "&description="+this.pagination.description;
axios.get("/books/"+ this.pagination.currentPage + "/" + this.pagination.pageSize + param).then((res)=>{
this.pagination.currentPage = res.data.data.current;
this.pagination.total = res.data.data.total;
this.pagination.pagesize = res.data.data.size;
this.dataList = res.data.data.records;
})
在钩子函数中调用getAll()函数
//钩子函数,VUE对象初始化完成后自动执行
created() {
this.getAll();
},
切换页码
//切换页码
handleCurrentChange(currentPage) {
this.pagination.currentPage = currentPage;
this.getAll();
},
//弹出添加窗口
handleCreate() {
this.dialogFormVisible = true;
this.resetForm();
},
//弹出编辑窗口
handleUpdate(row) {
axios.get("/books/"+row.id).then((res)=>{
if (res.data.flag && res.data.data != null){
this.formData = res.data.data;
this.dialogFormVisible4Edit = true;
}else {
this.$message.error("数据同步失败,自动刷新")
}
})
},
//重置表单
resetForm() {
this.formData = {};
},
//添加
handleAdd () {
axios.post("/books", this.formData).then((res)=>{
if (res.data.flag){
this.dialogFormVisible = false;
this.$message.success(res.data.message);
}else {
this.$message.error(res.data.message);
}
}).finally(()=>{
this.getAll();
});
},
// 删除
handleDelete(row) {
this.$confirm("此操作永久删除当前数据,是否继续?", "提示", {
type: 'info'
}).then(()=>{
axios.delete("/books/"+row.id).then((res)=>{
if (res.data.flag){
this.$message.success("删除成功")
}else {
this.$message.error("数据同步失败,自动刷新")
}
}).finally(()=>{
this.getAll();
});
}).catch(()=>{
this.$message.info("取消删除操作")
});
},
//修改
handleEdit() {
axios.put("/books", this.formData).then((res)=>{
if (res.data.flag){
this.dialogFormVisible4Edit = false;
this.$message.success("修改成功");
}else {
this.$message.error("修改失败");
}
}).finally(()=>{
this.getAll();
});
},
//取消
cancel(){
this.dialogFormVisible = false;
this.dialogFormVisible4Edit = false;
this.$message.info("操作取消")
},
业务消息一致性处理,当运行时发生异常导致数据格式不一致
需要对异常进行统一处理,出现异常后,返回指定格式R的信息
package com.example.controller.utils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class ProjectExceptionAdvice {
@ExceptionHandler({Exception.class})
public R doOtherException(Exception ex){
//记录日志
// 发送消息给运维
// 发送邮件给开发人员,ex对象发送给开发人员
ex.printStackTrace();
return new R("系统错误,请稍后再试!");
}
}