【SpringBoot】基于SpringBoot的SSMP整合案例

完整代码网盘链接:

链接:https://pan.baidu.com/s/1vKdsR-80C6t9yM7KXoX97g 
提取码:xasl

该案例简单实现数据的CRUD以及分页功能。

 

步骤:

  1. 实体类开发,使用Lombok
  2. Dao开发, 使用MybatisPlus
  3. Service开发,基于MyBatisPlus进行增量开发
  4. Controller开发, 使用Restful风格
  5. Controller开发, 前后端开发协议制作
  6. 页面开发,基于VUE + ElementUI
  7. 项目异常处理

1.  实体类开发,使用Lombok

导入依赖

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
            <version>1.18.4</version>
        </dependency>

实体类

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;
}

2. Dao开发, 使用MybatisPlus

1. 相关依赖

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.2</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.6</version>
        </dependency>

2. 配置数据源与MyBatisPlus对应的基础配置(id生成策略使用数据库自增策略)

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

3. 继承BaseMapper并指定泛型

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<Book> {
}

4. 为方便调试可以开启MyBatisPlus的日志 

mybatis-plus:
    configuration:
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

5. 添加分页拦截器

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;
    }
}

3. Service开发,基于MyBatisPlus进行增量开发

1. 接口定义(分页和结合模糊查询的分页查询)

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<Book> {
    IPage<Book> getPage(Integer currentPage, Integer pageSize);

    IPage<Book> getPage(Integer currentPage, Integer pageSize, Book book);
}

2. 实现类定义

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<BookDao, Book> implements IBookService {

    @Autowired
    private BookDao bookDao;
    @Override
    public IPage<Book> getPage(Integer currentPage, Integer pageSize) {
        IPage<Book> page = new Page<>(currentPage, pageSize);
        IPage<Book> bookIPage = bookDao.selectPage(page, null);
        return bookIPage;
    }

    @Override
    public IPage<Book> getPage(Integer currentPage, Integer pageSize, Book book) {
        IPage<Book> page = new Page<>(currentPage, pageSize);
        LambdaQueryWrapper<Book> lqw = new LambdaQueryWrapper<Book>();
        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);
    }
}

4. Controller开发, 使用Restful风格

1. 基于Restful进行表现层接口开发

2. 表现层消息一致性处理,也就是统一返回数据的格式

3. 设计一个格式类R,让返回的格式都为R格式

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<Book> page = iBookService.getPage(currentPage, pageSize, book);
        if (currentPage > page.getPages()){
            page = iBookService.getPage((int)page.getPages(), pageSize);
        }
        return new R(null != page, page);
    }
}

5. 页面开发

1. 列表页(直接结合模糊查询加分页)

在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();
            },

2. 弹出添加页面或者编辑页面(需要有编辑的数据内容填充)

//弹出添加窗口
            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("数据同步失败,自动刷新")
                    }

                })
            },

3. 重置表单

//重置表单
            resetForm() {
                this.formData = {};
            },

4. 添加数据,删除数据,修改数据

//添加
            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();
                });
            },

5. 取消操作,也就是关闭添加或者修改页面

//取消
            cancel(){
                this.dialogFormVisible = false;
                this.dialogFormVisible4Edit = false;
                this.$message.info("操作取消")
            },

7. 项目异常处理

业务消息一致性处理,当运行时发生异常导致数据格式不一致

需要对异常进行统一处理,出现异常后,返回指定格式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("系统错误,请稍后再试!");
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Leo&&Eva

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值