java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Springboot整合mybatisplus

Springboot整合mybatisplus的项目实战

作者:苏雪夜酒

本文主要介绍了Springboot整合mybatisplus的项目实战,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

Springboot整合mybatisplus,纯后端,验证结果是通过postman调用的,记录一下

1、建表语句以及初始化数据脚本

CREATE TABLE `tbl_book` (
  `id` int NOT NULL AUTO_INCREMENT,
  `type` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  `name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  `description` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=10014 DEFAULT CHARSET=utf8
INSERT INTO `tbl_book` VALUES (10000, '计算机理论', 'Java编程思想(第4版)', 'Java学习经典,殿堂级著作!赢得了全球程序员的广泛赞誉。');
INSERT INTO `tbl_book` VALUES (10001, '计算机理论', '计算机组成原理', '资深的计算机体系结构教育家Alan Clements博士编写,涵盖计算机系统的组成和体系结构的基本概念、指令系统以及处理器实现等涉及计算机组成原理课程的内容。');
INSERT INTO `tbl_book` VALUES (10002, '程序设计', 'C++ Primer Plus 第6版 中文版', 'C++程序设计经典教程,畅销30年的C++大百科全书全新升级,经典C++入门教程十年新版再现\')');
INSERT INTO `tbl_book` VALUES (10003, '程序设计', 'RocketMQ技术内幕:RocketMQ架构设计与实现原理(第2版)', '畅销书升级,RocketMQ创始人高度评价,深入源码分析技术架构和实现原理,打造高性能、高可用、高吞吐量、低延迟RocketMQ');
INSERT INTO `tbl_book` VALUES (10004, '程序设计', ' 深入理解Java虚拟机:JVM高级特性与实践(第3版)', '周志明虚拟机新作,第3版新增内容近50%,5个维度全面剖析JVM,大厂面试知识点全覆盖。与 Java编程思想、Effective Java、Java核心技术 堪称:Java四大名著');
INSERT INTO `tbl_book` VALUES (10005, '历史', '见识城邦·人类简史:从动物到上帝(新版)', '以色列新锐历史学家尤瓦尔·赫拉利代表作,第十届文津图书奖获奖作品');
INSERT INTO `tbl_book` VALUES (10006, '历史', '中国通史', '吕思勉先生写给普通读者的中国通史入门书,用白话文写成的中国通史,把历史从“帝王的家谱”转变为人类的进化史');
INSERT INTO `tbl_book` VALUES (10007, '哲学', '理想国(柏拉图代表作)', '奠定西方哲学史的源流之作。2021新译本,以斯灵斯校勘本为底本,遵照“字对字”的原则,从古希腊原文直译,兼顾准确性和语言通顺性,助你读懂理想国。');
INSERT INTO `tbl_book` VALUES (10008, '哲学', '苏格拉底的申辩', '《柏拉图注疏集:苏格拉底的申辩》记述的是公元前399年,一个叫莫勒图斯的年轻人在雅典状告哲学家苏格拉底,说他不信城邦诸神,引进新的精灵之事,败坏青年。 于是,苏格拉底被传讯,在500人组成的陪审团面前作了著名的申辩。');
INSERT INTO `tbl_book` VALUES (10009, '文学', '鲁迅全集', '大师全集,完整收录,鲁迅毕生之心血尽归于此。\r\n\r\n  鲁迅是中国20世纪的文学家、思想家、革命家,中国近代文学巨匠。他早年留学于日本,后来弃医从文,他用笔耕不辍的文字为新一代青年们指引方向,在国内外思想文化领域有着极高的声誉。');
INSERT INTO `tbl_book` VALUES (10010, '文学', '人间清醒', '茅盾文学奖获得者梁晓声2021全新力作');
INSERT INTO `tbl_book` VALUES (10011, '经济', '八次危机:中国的真实经验1949-2009', '著名“三农”专家温铁军,用经济的独特视角,重新审视中国的1949-2009,历史给我了我们怎样的真实经验?');

2、项目目录

3、pom文件

<?xml version="1.0" encoding="UTF-8"?>
<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.1.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>springboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>8</java.version>
    </properties>
    <dependencies>
        <!--web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--mysql-connector-->
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.20</version>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--mybatis-plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.1</version>
        </dependency>
        <!--druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.6</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

4、application文件

spring:
  datasource:
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/myproject?serverTimezone=UTC
      username: root
      password: root
mybatis-plus:
  global-config:
    db-config:
      table-prefix: tbl_
      id-type: auto
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl  #开启MP运行日志信息

5、PO类以及VO类

package com.example.po;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Book {
    private Integer id;
    private String type;
    private String name;
    private String description;
}
package com.example.vo;
/**
 * 供页面显示使用的类
 */
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class BookVo {
    private String type;
    private String name;
    private String description;
}

6、Dao层

package com.example.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.po.Book;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
@Mapper
@Component
public interface BookDao extends BaseMapper<Book> {
}

7、service以及实现类

package com.example.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.po.Book;
/**
 * 基于 mybatisplus 实现CRUD快速开发
 */
public interface IBookService extends IService<Book> {
    IPage<Book> getPage(Integer currentPage,Integer pageSize);
    IPage<Book> 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.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.po.Book;
import com.example.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
@Service
public class IBookServiceImpl extends ServiceImpl<BookDao, Book> implements IBookService {
    @Autowired
    private BookDao bookDao;
    @Override
    public IPage<Book> getPage(Integer currentPage, Integer pageSize) {
        Page<Book> page = new Page<>(currentPage,pageSize);
        bookDao.selectPage(page,null);
        return page;
    }
    @Override
    public IPage<Book> getPage(Integer currentPage, Integer pageSize, Book book) {
        LambdaQueryWrapper<Book> queryWrapper = new LambdaQueryWrapper<Book>();
        queryWrapper.like(!StringUtils.isEmpty(book.getType()),Book::getType,book.getType());
        queryWrapper.like(!StringUtils.isEmpty(book.getName()),Book::getName,book.getName());
        queryWrapper.like(!StringUtils.isEmpty(book.getDescription()),Book::getDescription,book.getDescription());
        Page<Book> page = new Page<>(currentPage,pageSize);
        bookDao.selectPage(page,queryWrapper);
        return page;
    }
}

8、controller层

package com.example.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.global.PlatErrorCodeEnum;
import com.example.po.Book;
import com.example.global.Response;
import com.example.global.ResponseBuilder;
import com.example.service.IBookService;
import com.example.vo.BookVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private IBookService bookService;
    //查询所有数据
    @GetMapping
    public Response<List<BookVo>> getBooks(){
        List<BookVo> bookList = bookService.list().stream().map(po -> {
            BookVo vo = new BookVo();
            //将两个字段相同的对象进行属性值的复制
            BeanUtils.copyProperties(po, vo);
            return vo;
        }).collect(Collectors.toList());
        return ResponseBuilder.buildNormalResponse(bookList);
    }
    //添加数据
    @PostMapping("/save")
    public Response<Boolean> saveBook(@RequestBody Book book){
        Boolean flag = bookService.save(book);
        return flag == true ? ResponseBuilder.buildNormalResponse() : ResponseBuilder.buildErrorResponse(PlatErrorCodeEnum.ADD_DATA_FAILED);
    }
    @PutMapping("/update")
    public Response<Boolean> updateBook(@RequestBody Book book){
        boolean flag = bookService.updateById(book);
        return flag == true ? ResponseBuilder.buildNormalResponse() : ResponseBuilder.buildErrorResponse(PlatErrorCodeEnum.UPDATE_DATA_FAILED);
    }
    //查询单个数据
    @GetMapping("{id}")
    public Response<BookVo> getBookById(@PathVariable Integer id){
        Book book = bookService.getById(id);
        BookVo vo = new BookVo();
        BeanUtils.copyProperties(book,vo);
        return ResponseBuilder.buildNormalResponse(vo);
    }
    //删除单个数据
    @DeleteMapping("{id}")
    public Response<Boolean> deleteBook(@PathVariable Integer id){
        boolean flag = bookService.removeById(id);
        return flag == true ? ResponseBuilder.buildNormalResponse() : ResponseBuilder.buildErrorResponse(PlatErrorCodeEnum.DELETE_DATA_FAILED);
    }
    //分页查询数据
    @GetMapping("{currentPage}/{pageSize}")
    public Response<List<BookVo>> getBooksByPage(@PathVariable Integer currentPage,@PathVariable Integer pageSize){
        IPage<Book> page = bookService.getPage(currentPage,pageSize);
        //避免查出来所有的数据,增加一个vo类,只展示需要的字段
        List<BookVo> bookVos = page.getRecords().stream().map(po -> {
            BookVo vo = new BookVo();
            //将两个字段相同的对象进行属性值的复制
            BeanUtils.copyProperties(po, vo);
            return vo;
        }).collect(Collectors.toList());
        return ResponseBuilder.buildNormalResponse(bookVos);
    }
}

9、为了给前端返回统一的值,再加一些优化

package com.example.global;
public enum PlatErrorCodeEnum {
    ADD_DATA_FAILED("10000", "添加数据失败"),
    UPDATE_DATA_FAILED("10001", "更新数据失败"),
    DELETE_DATA_FAILED("10001", "删除数据失败") ;
    public static final String ERROR_CODE="000";
    private String code;
    private String message;
    PlatErrorCodeEnum(String code, String message) {
        this.code = code;
        this.message = message;
    }
    public String getCode() {
        return code;
    }
    public String getMessage() {
        return message;
    }
}
package com.example.global;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
@Data
@ToString(callSuper = true)
public class Response<T> implements Serializable {
    private static final long serialVersionUID = -2644259941898334897L;
    private String returnCode;
    private String returnMsg;
    private T returnData;
    public Response(){
    }
    public Response(String returnCode){
        this.returnCode = returnCode;
    }
    public Response(String returnCode, String returnMsg){
        this.returnCode = returnCode;
        this.returnMsg = returnMsg;
    }
    public Response(String returnCode, String returnMsg, T returnData){
        this.returnCode = returnCode;
        this.returnMsg = returnMsg;
        this.returnData = returnData;
    }
    public T getReturnData() {
        return returnData;
    }
    public Response<T> setReturnData(T returnData) {
        this.returnData = returnData;
        return this;
    }
}
package com.example.global;
/**
 * 构造响应结果
 */
public final class ResponseBuilder {
    /**
     * 返回成功.
     */
    public static final String RESPONSE_OK = "0000";
    public static final String RESPONSE_MESSAGE = "响应成功";
    /**
     * 构造一个失败响应
     */
    public static <T> Response<T> buildErrorResponse(PlatErrorCodeEnum enums) {
        Response<T> entity = new Response<>();
        entity.setReturnCode(String.valueOf(enums.getCode()));
        entity.setReturnMsg(enums.getMessage());
        return entity;
    }
    /**
     * 构造一个失败响应
     */
    public static <T> Response<T> buildErrorResponse(String error, String message) {
        Response<T> entity = new Response<>();
        entity.setReturnCode(error);
        entity.setReturnMsg(message);
        return entity;
    }
    /**
     * 构造一个正常的没有返回数据的响应
     */
    public static <T> Response<T> buildNormalResponse() {
        return new Response<T>(RESPONSE_OK, RESPONSE_MESSAGE);
    }
    /**
     * 构造一个正常的有返回数据的响应
     * @param returnData
     * @param <T>
     * @return
     */
    public static <T> Response<T> buildNormalResponse(T returnData) {
        Response<T> entity = buildNormalResponse();
        entity.setReturnData(returnData);
        return entity;
    }
}

10、mybatisplus分页插件配置

package com.example.config;
/**
 * 配置mybatisplus分页插件
 */
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@MapperScan("com.example.dao")
public class MyBatisPlusConf {
    @Bean
    public PaginationInterceptor mybatisPlusInterceptor(){
        //创建拦截器 SpringBoot 低版本用 PaginationInterceptor 高版本用 MybatisPlusInterceptor
        PaginationInterceptor interceptor = new PaginationInterceptor();
        return interceptor;
    }
}

到此这篇关于Springboot整合mybatisplus的项目实战的文章就介绍到这了,更多相关Springboot整合mybatisplus 内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文