springBoot,mp,ssm整合案例

控制层

java 复制代码
package com.spring.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.spring.controller.untils.R;
import com.spring.domain.Book;
import com.spring.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping( "/books")
public class BookController2 {
    @Autowired
    private IBookService bookService;
    @Autowired
    RedisTemplate redisTemplate;

//    @RequestMapping("addname")
//    public String addStr(){
//        redisTemplate.opsForValue().set("name","zhangsan");
//        return "success";
//    }
    @GetMapping
    public R selectAll(){
        return new R(true,bookService.list());
    }
    //添加操作
    @PostMapping
    public R save(@RequestBody Book book) throws IOException {
        if (book.getName().equals("张三")){
            throw new IOException();
        }
        boolean flag = bookService.save(book);
        return new R(flag , flag ? "添加成功":"添加失败");
    }
    //修改操作
    @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.removeById(id));
    }
//    查询操作
    @GetMapping("/{id}")
    public R getById(@PathVariable Integer id){
        return new R(true,bookService.getById(id));
    }
//    @GetMapping("{currentPage}/{pageSize}")
//    public R getPage(@PathVariable Integer currentPage,@PathVariable Integer pageSize){
//        IPage<Book> page = bookService.getPage(currentPage, pageSize);
//        //如果当前页码超过最大页码,则显示最后一页
//        if (currentPage>page.getPages()){
//            page = bookService.getPage((int) page.getPages(), pageSize);
//        }
//        return new R(true,page);
//    }


    @GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable Integer currentPage,@PathVariable Integer pageSize,Book book){
//        System.out.println("book" + 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);
    }
}

工具类,返回json格式

java 复制代码
package com.spring.controller.untils;
import lombok.Data;



public class R {
    private boolean flag;
    private Object data;
    private String msg;
    public R() {
    }
    public R(boolean flag) {
        this.flag = flag;
    }

    public R(boolean flag, Object data) {
        this.flag = flag;
        this.data = data;
    }
    public R(boolean flag,String msg) {
        this.flag = flag;
        this.msg = msg;
    }
    

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }
}

实体类

java 复制代码
package com.spring.domain;

import lombok.Data;

import java.io.Serializable;

@Data
public class Book implements Serializable {
private Integer id;
private String type;
private String name;
private String description ;

    public Book() {
    }

    public Book(Integer id, String type, String name, String description) {
        this.id = id;
        this.type = type;
        this.name = name;
        this.description = description;
    }

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", type='" + type + '\'' +
                ", name='" + name + '\'' +
                ", description='" + description + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

dao层

java 复制代码
package com.spring.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.spring.domain.Book;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface BookDao extends BaseMapper<Book> {
}

service层

java 复制代码
package com.spring.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.spring.domain.Book;

public interface IBookService extends IService<Book> {
    IPage<Book> getPage(int currentPage, int pageSize);
    IPage<Book> getPage(int currentPage, int pageSize,Book book);
}

实现类

java 复制代码
package com.spring.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.spring.dao.BookDao;
import com.spring.domain.Book;
import com.spring.service.IBookService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class BookServiceImpl2 extends ServiceImpl<BookDao, Book> implements IBookService {
    @Autowired
    private BookDao bookDao;
    @Override
    public IPage<Book> getPage(int currentPage, int pageSize) {
        IPage<Book> page = new Page<>(currentPage,pageSize);
        bookDao.selectPage(page,null);
        return page;
    }

    @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<Book> page = new Page<>(currentPage,pageSize);
        bookDao.selectPage(page,lqw);
        return page;
    }
}

前端网页

html 复制代码
<!DOCTYPE html>

<html>

<head>

    <!-- 页面meta -->

    <meta charset="utf-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <title>基于SpringBoot整合SSM案例</title>

    <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">

    <!-- 引入样式 -->

    <link rel="stylesheet" href="../plugins/elementui/index.css">

    <link rel="stylesheet" href="../plugins/font-awesome/css/font-awesome.min.css">

    <link rel="stylesheet" href="../css/style.css">

</head>

<body class="hold-transition">

<div id="app">

    <div class="content-header">

        <h1>图书管理</h1>

    </div>

    <div class="app-container">

        <div class="box">

            <div class="filter-container">
                <!--查询条件-->
                <el-input placeholder="图书类别" v-model="pagination.type" style="width: 200px;" class="filter-item"></el-input>
                <el-input placeholder="图书名称" v-model="pagination.name" style="width: 200px;" class="filter-item"></el-input>
                <el-input placeholder="图书描述" v-model="pagination.description" style="width: 200px;" class="filter-item"></el-input>
                <el-button @click="getAll()" class="dalfBut">查询</el-button>
                <el-button type="primary" class="butT" @click="handleCreate()">新建</el-button>
            </div>


<!--            size="small":设置表格的整体尺寸为小。
                current-row-key="id":指定当前选中行的唯一标识字段为id,用于高亮显示当前行。
                :data="dataList":通过绑定属性data将dataList数组作为表格的数据源。
                stripe:开启斑马条纹样式,使表格更易读。
                highlight-current-row:高亮显示当前选中行-->
            <el-table size="small" current-row-key="id" :data="dataList" stripe highlight-current-row>

                <el-table-column type="index" align="center" label="序号"></el-table-column>

                <el-table-column prop="type" label="图书类别" align="center"></el-table-column>

                <el-table-column prop="name" label="图书名称" align="center"></el-table-column>

                <el-table-column prop="description" label="描述" align="center"></el-table-column>

                <el-table-column label="操作" align="center">
<!--                    使用作用域插槽,scope对象包含当前行的数据-->
                    <template slot-scope="scope">

                        <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>

                        <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>

                    </template>

                </el-table-column>

            </el-table>

            <!--分页组件-->
            <div class="pagination-container">

                <el-pagination
                        class="pagiantion"

                        @current-change="handleCurrentChange"

                        :current-page="pagination.currentPage"

                        :page-size="pagination.pageSize"

                        layout="total, prev, pager, next, jumper"

                        :total="pagination.total">

                </el-pagination>

            </div>

            <!-- 新增标签弹层 -->

            <div class="add-form">

                <el-dialog title="新增图书" :visible.sync="dialogFormVisible">

                    <el-form ref="dataAddForm" :model="formData" :rules="rules" label-position="right" label-width="100px">

                        <el-row>

                            <el-col :span="12">

                                <el-form-item label="图书类别" prop="type">

                                    <el-input v-model="formData.type"/>

                                </el-form-item>

                            </el-col>

                            <el-col :span="12">

                                <el-form-item label="图书名称" prop="name">

                                    <el-input v-model="formData.name"/>

                                </el-form-item>

                            </el-col>

                        </el-row>


                        <el-row>

                            <el-col :span="24">

                                <el-form-item label="描述">

                                    <el-input v-model="formData.description" type="textarea"></el-input>

                                </el-form-item>

                            </el-col>

                        </el-row>

                    </el-form>

                    <div slot="footer" class="dialog-footer">

                        <el-button @click="cancel()">取消</el-button>

                        <el-button type="primary" @click="handleAdd()">确定</el-button>

                    </div>

                </el-dialog>

            </div>

            <!-- 编辑标签弹层 -->

            <div class="add-form">

                <el-dialog title="编辑检查项" :visible.sync="dialogFormVisible4Edit">

                    <el-form ref="dataEditForm" :model="formData" :rules="rules" label-position="right" label-width="100px">

                        <el-row>

                            <el-col :span="12">

                                <el-form-item label="图书类别" prop="type">

                                    <el-input v-model="formData.type"/>

                                </el-form-item>

                            </el-col>

                            <el-col :span="12">

                                <el-form-item label="图书名称" prop="name">

                                    <el-input v-model="formData.name"/>

                                </el-form-item>

                            </el-col>

                        </el-row>

                        <el-row>

                            <el-col :span="24">

                                <el-form-item label="描述">

                                    <el-input v-model="formData.description" type="textarea"></el-input>

                                </el-form-item>

                            </el-col>

                        </el-row>

                    </el-form>

                    <div slot="footer" class="dialog-footer">

                        <el-button @click="cancel()">取消</el-button>

                        <el-button type="primary" @click="handleEdit()">确定</el-button>

                    </div>

                </el-dialog>

            </div>

        </div>

    </div>

</div>

</body>

<!-- 引入组件库 -->

<script src="../js/vue.js"></script>

<script src="../plugins/elementui/index.js"></script>

<script type="text/javascript" src="../js/jquery.min.js"></script>

<script src="../js/axios-0.18.0.js"></script>

<script>
    var vue = new Vue({
        el: '#app',
        data:{
            dataList: [],//当前页要展示的列表数据
            dialogFormVisible: false,//添加表单是否可见
            dialogFormVisible4Edit:false,//编辑表单是否可见
            formData: {},//表单数据
            rules: {//校验规则
                type: [{ required: true, message: '图书类别为必填项', trigger: 'blur' }],
                name: [{ required: true, message: '图书名称为必填项', trigger: 'blur' }]
            },
            pagination: {//分页相关模型数据
                currentPage: 1,//当前页码
                pageSize:10,//每页显示的记录数
                total:0,//总记录数
                type: "",
                name: "",
                description: ""
            }
        },

        //钩子函数,VUE对象初始化完成后自动执行
        created() {
            //调用查询全部数据的操作
            this.getAll();
        },

        methods: {
            //列表
            // getAll() {
            //     console.log("run")
            //     //发送异步请求,注意这个请求必须是前面控制层访问过的
            //     axios.get("/books").then((res)=>{
            //         console.log(res.data);
            //     //res:通常表示从服务器返回的响应对象
            //     // res.data:响应对象中的 data 属性,通常包含服务器返回的实际数据
            //     //res.data.data:得到数据库的值
            //         this.dataList = res.data.data;
            //     })
            // },

            //分页查询
            getAll() {
                //组织参数,拼接url请求地址
                // console.log(this.pagination.type);
                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;
                    //因为使用了分页插件,所以还需要调用records
                    //records 是一个数组,通常包含从服务器查询到的多条记录
                    this.dataList = res.data.data.records;
                });
            },

            //切换页码
            handleCurrentChange(currentPage) {
                //修改页码值为当前选中的页码值
                this.pagination.currentPage = currentPage;
                //执行查询
                this.getAll();
            },

            //弹出添加窗口
            handleCreate() {
                //因为上面的dialogFormVisible是false,所以这里要设置为true
                this.dialogFormVisible = true;
                //重置表单
                this.resetForm();
            },
            //添加
            handleAdd () {
                axios.post("/books",this.formData).then((res)=>{
                    //判断操作是否成功,添加完毕后关闭弹窗
                    if(res.data.flag){
                        //添加成功
                        this.dialogFormVisible = false;
                        //弹窗显示添加成功
                        this.$message.success(res.data.msg)
                    }else{
                        this.$message.error(res.data.msg);
                    }
                }).finally(()=>{
                    //不管成功与否都要重新加载datalist数据
                    this.getAll();
                });
            },
            //
            //取消
            cancel(){
                this.dialogFormVisible = false;
                this.dialogFormVisible4Edit = false;
                this.$message.info("当前操作取消");
            },

            // 删除
            handleDelete(row) {
                console.log(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(()=>{
                        //2.重新加载数据
                        this.getAll();
                    });
                }).catch(()=>{
                    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(()=>{
                    //2.重新加载数据
                    this.getAll();
                });
            },

            //修改
            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();
                });
            },

            //条件查询
        }
    })

</script>

</html>

yml配置

html 复制代码
server:
  port: 8022
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatisplus?serverTimezone=UTC
    username: root
    password: root
    type: com.alibaba.druid.pool.DruidDataSource
mybatis-plus:
  global-config:
    db-config:
      table-prefix: tbl_
      id-type: auto
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

分页查询拦截器

java 复制代码
package com.spring.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.context.annotation.Configuration;
import org.springframework.stereotype.Component;

@Configuration
public class mpconfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor interceptor=new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return interceptor;
    }
}
相关推荐
吾日三省吾码1 小时前
JVM 性能调优
java
oi773 小时前
使用itextpdf进行pdf模版填充中文文本时部分字不显示问题
java·服务器
2401_857610033 小时前
SpringBoot社团管理:安全与维护
spring boot·后端·安全
少说多做3433 小时前
Android 不同情况下使用 runOnUiThread
android·java
知兀3 小时前
Java的方法、基本和引用数据类型
java·笔记·黑马程序员
蓝黑20203 小时前
IntelliJ IDEA常用快捷键
java·ide·intellij-idea
Ysjt | 深3 小时前
C++多线程编程入门教程(优质版)
java·开发语言·jvm·c++
凌冰_3 小时前
IDEA2023 SpringBoot整合MyBatis(三)
spring boot·后端·mybatis