基于SpringBoot的SSMP整合案例

简介:SSMP(Spring+SpringMVC+MyBatis),通过SpringBoot整合SSMP来完成增删改查案例。

功能开发模块

  1. 实体类开发————使用Lombok快速制作实体类
  2. Dao开发————整合MyBatisPlus,制作数据层测试
  3. Service开发————基于MyBatisPlus进行增量开发,制作业务层测试类
  4. Controller开发————基于Restful开发,使用PostMan测试接口功能
  5. Controller开发————前后端开发协议制作
  6. 页面开发————基于VUE+ElementUI制作,前后端联调,页面数据处理,页面消息处理
    • 列表
    • 新增
    • 修改
    • 删除
    • 分页
    • 查询
  7. 项目异常处理
  8. 按条件查询————页面功能调整、Controller修正功能、Service修正功能

创建模块

数据层(Dao层)操作

创建项目


pom.xml

需要添加mybatis-plus的配置文件。

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">    <modelVersion>4.0.0</modelVersion>    <parent>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-parent</artifactId>        <version>2.7.6</version>        <relativePath/>     </parent>    <groupId>com.example</groupId>    <artifactId>SpringBootSSMP</artifactId>    <version>0.0.1-SNAPSHOT</version>    <name>SpringBootSSMP</name>    <description>SpringBootSSMP</description>    <properties>        <java.version>17</java.version>    </properties>    <dependencies>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-web</artifactId>        </dependency>        <dependency>            <groupId>com.baomidou</groupId>            <artifactId>mybatis-plus-boot-starter</artifactId>            <version>3.4.3</version>        </dependency>        <dependency>            <groupId>com.alibaba</groupId>            <artifactId>druid-spring-boot-starter</artifactId>            <version>1.2.6</version>        </dependency>        <dependency>            <groupId>mysql</groupId>            <artifactId>mysql-connector-java</artifactId>            <scope>runtime</scope>        </dependency>                <dependency>            <groupId>org.projectlombok</groupId>            <artifactId>lombok</artifactId>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-test</artifactId>            <scope>test</scope>        </dependency>    </dependencies>    <build>        <plugins>            <plugin>                <groupId>org.springframework.boot</groupId>                <artifactId>spring-boot-maven-plugin</artifactId>            </plugin>        </plugins>    </build></project>

创建数据库

-- ------------------------------ Table structure for tbl_book-- ----------------------------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 = InnoDB AUTO_INCREMENT = 51 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;-- ------------------------------ Records of tbl_book-- ----------------------------INSERT INTO `tbl_book` VALUES (1, '计算机理论', 'Spring实战 第5版', 'Spring入门经典教程,深入理解Spring原理技术内幕');INSERT INTO `tbl_book` VALUES (2, '计算机理论', 'Spring 5核心原理与30个类手写实战', '十年沉淀之作,手写Spring精华思想');INSERT INTO `tbl_book` VALUES (3, '计算机理论', 'Spring 5 设计模式', '深入Spring源码剖析Spring源码中蕴含的10大设计模式');INSERT INTO `tbl_book` VALUES (4, '计算机理论', 'Spring MVC+MyBatis开发从入门到项目实战', '全方位解析面向Web应用的轻量级框架,带你成为Spring MVC开发高手');INSERT INTO `tbl_book` VALUES (5, '计算机理论', '轻量级Java Web企业应用实战', '源码级剖析Spring框架,适合已掌握Java基础的读者');INSERT INTO `tbl_book` VALUES (6, '计算机理论', 'Java核心技术 卷I 基础知识(原书第11版)', 'Core Java 第11版,Jolt大奖获奖作品,针对Java SE9、10、11全面更新');INSERT INTO `tbl_book` VALUES (7, '计算机理论', '深入理解Java虚拟机', '5个维度全面剖析JVM,大厂面试知识点全覆盖');INSERT INTO `tbl_book` VALUES (8, '计算机理论', 'Java编程思想(第4版)', 'Java学习必读经典,殿堂级著作!赢得了全球程序员的广泛赞誉');INSERT INTO `tbl_book` VALUES (9, '计算机理论', '零基础学Java(全彩版)', '零基础自学编程的入门图书,由浅入深,详解Java语言的编程思想和核心技术');INSERT INTO `tbl_book` VALUES (10, '市场营销', '直播就该这么做:主播高效沟通实战指南', '李子柒、李佳琦、薇娅成长为网红的秘密都在书中');INSERT INTO `tbl_book` VALUES (11, '市场营销', '直播销讲实战一本通', '和秋叶一起学系列网络营销书籍');INSERT INTO `tbl_book` VALUES (12, '市场营销', '直播带货:淘宝、天猫直播从新手到高手', '一本教你如何玩转直播的书,10堂课轻松实现带货月入3W+');

yml

server:  port: 80spring:  datasource:    druid:      driver-class-name: com.mysql.cj.jdbc.Driver      url: jdbc:mysql://localhost:3306/mybatis" />

lonbok实体类快速开发

简介:一个提供一组注解来简化POJO实体类的开发的Java库。

导入依赖

<dependency>    <groupId>org.projectlombok</groupId>    <artifactId>lombok</artifactId></dependency>

创建Book类

package com.example.springbootssmp.domain;//lombokimport lombok.Data;@Data// @Data注解实现了类的除了构造方法外的所有方法的自动生成,大大简化了开发public class Book {    private Integer id;    private String type;    private String name;    private String description;}

创建BookDao

package com.example.springbootssmp.dao;import com.baomidou.mybatisplus.core.mapper.BaseMapper;import com.example.springbootssmp.domain.Book;import org.apache.ibatis.annotations.Mapper;@Mapperpublic interface BookDao extends BaseMapper<Book> {}

数据层开发(实现基础的CRUD)

测试dao层

测试代码
测试基本的增删改查

@SpringBootTestpublic class BookDaoTestCase {    @Autowired    private BookDao bookDao;    @Test    void testGetById(){        System.out.println(bookDao.selectById(1));    }    @Test    void testSave(){        Book book = new Book();        book.setType("测试数据123");        book.setName("测试数据123");        book.setDescription("测试数据123");        bookDao.insert(book);    }    @Test    void testUpdate(){        Book book = new Book();        book.setId(17);        book.setType("测试数据abcdefg");        book.setName("测试数据123");        book.setDescription("测试数据123");        bookDao.updateById(book);    }    @Test    void testDelete(){        bookDao.deleteById(16);    }    @Test    void testGetAll(){        bookDao.selectList(null);    }    }

分页查询

创建配置文件

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;@Configurationpublic class MPConfig {    @Bean    public MybatisPlusInterceptor mybatisPlusInterceptor(){        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());        return interceptor;    }}

测试代码

@Testvoid testGetPage(){    IPage page = new Page(2,5); // 从第二页开始查 每页最多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(page.getRecords());}

运行结果

条件查询

@Test    void testGetBy(){        QueryWrapper<Book> qw = new QueryWrapper<>();        // like 条件模糊查询 查询name like Spring的 %Spring%的样子的        qw.like("name","Spring");        System.out.println(bookDao.selectList(qw));    }    @Test    void testGetBy2(){        String name = "1";        LambdaQueryWrapper<Book> lqw = new LambdaQueryWrapper<Book>();        //if(name != null) lqw.like(Book::getName,name);        lqw.like(name != null,Book::getName,name);  // 查询之前先看看name是否为空        System.out.println(bookDao.selectList(lqw));    }


业务层(Service)

概述:Service实现对Dao层的控制,即业务层对数据层的控制。

注意:需要注意的是,Service的方法命名的方式需要与Dao层有所区别一点,防止搞混。

基础CRUD

方式一(原始开发)
BookService.java

public interface BookService {    Boolean save(Book book);    Boolean update(Book book);    Boolean delete(Integer id);    Book getById(Integer id);    List<Book> getAll();    IPage<Book> getPage(int currentPage,int pageSize);}

BookServiceImpl.java

@Servicepublic class BookServiceImpl implements BookService {    @Autowired    private BookDao bookDao;    @Override    public Boolean save(Book book) {        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);    }    @Override    public IPage<Book> getPage(int currentPage, int pageSize) {        IPage page = new Page(currentPage,pageSize);        bookDao.selectPage(page,null);        return page;    }}

方式二(业务快速开发)
文件结构

IBookService.java

public interface IBookService extends IService<Book> {//添加非通用操作API接口    boolean saveBook(Book book);    boolean modify(Book book);    boolean delete(Integer id);    IPage<Book> getPage(int currentPage, int pageSize);    IPage<Book> getPage(int currentPage, int pageSize, Book book);}

BookServiceImpl.java

@Servicepublic class BookServiceImpl extends ServiceImpl<BookDao, Book> implements IBookService {    @Autowired    private BookDao bookDao;//添加非通用操作API    @Override    public boolean saveBook(Book book) {        return bookDao.insert(book) > 0;    }    @Override    public boolean modify(Book book) {        return bookDao.updateById(book) > 0;    }    @Override    public boolean delete(Integer id) {        return bookDao.deleteById(id) > 0;    }    @Override    public IPage<Book> getPage(int currentPage, int pageSize) {        IPage 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<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());        IPage page = new Page(currentPage,pageSize);        bookDao.selectPage(page,lqw);        return page;    }}

测试类
文件结构

BookServiceTest.java

@SpringBootTestpublic class BookServiceTest {    @Autowired    private IBookService bookService;    @Test    void testGetById(){        System.out.println(bookService.getById(4));    }    @Test    void testSave(){        Book book = new Book();        book.setType("测试数据123");        book.setName("测试数据123");        book.setDescription("测试数据123");        bookService.save(book);    }    @Test    void testUpdate(){        Book book = new Book();        book.setId(17);        book.setType("-----------------");        book.setName("测试数据123");        book.setDescription("测试数据123");        bookService.updateById(book);    }    @Test    void testDelete(){        bookService.removeById(18);    }    @Test    void testGetAll(){        bookService.list();    }    @Test    void testGetPage(){        IPage<Book> page = new Page<Book>(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(page.getRecords());    }}

运行结果

表现层(Controller)

这里的Restful风格需要参考这篇文章:restful风格快速入门
接受参数:

  • 实体数据:@RequestBody
  • 路径变量:@PathVariable

方式一

package com.example.springbootssmp.controller;import com.baomidou.mybatisplus.core.metadata.IPage;import com.example.springbootssmp.domain.Book;import com.example.springbootssmp.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 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.modify(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, null);    }}

方式一存在着问题,问题在于对于返回的数据,没有一个标识,使得我们知道数据是否查询成功,如果查询失败了,怎么返回失败的信息,于是我们就在方式二中进行了完善。
这些问题导致了没有没有一个统一的返回值结果,不便于前端开发的读取数据,于是在方式二中就创建了Tool类的前后端协议。

方式二
创建util包的Tool

package com.example.springbootssmp.controller.util;import lombok.Data;@Datapublic class Tool {    private Boolean flag; // 查询是否成功    private Object data;  // 查询获得的数据    private String msg; // 返回的信息     public Tool(){}    public Tool(Boolean flag){        this.flag = flag;    }    public Tool(Boolean flag,Object data){        this.flag = flag;        this.data = data;    }    public Tool(Boolean flag,String msg){        this.flag = flag;        this.msg = msg;    }    public Tool(String msg){        this.flag = false;        this.msg = msg;    }}

完善BookController

@RestController@RequestMapping("/books")public class BookController { @Autowired private IBookService bookService; @GetMapping public Tool getAll(){ return new Tool(true, bookService.list()); } @PostMapping public Tool save(@RequestBody Book book) throws IOException { if (book.getName().equals("123") ) throw new IOException(); boolean flag = bookService.save(book); return new Tool(flag, flag " />



最后的运行结果
访问地址:http://localhost/pages/books.html