SpringBoot 如何集成 MyBatisPlus(梦到自己不停的找东西)

  本篇文章为你整理了SpringBoot 如何集成 MyBatisPlus(梦到自己不停的找东西)的详细内容,包含有herman melville写作特点英文 梦到自己不停的找东西 邵阳市二纺机医院 陆风x7水箱在哪排空气 SpringBoot 如何集成 MyBatisPlus,希望能帮助你了解 SpringBoot 如何集成 MyBatisPlus。

  程序员优雅哥 (youyacoder)

  程序员优雅哥 (公众号同名,第一时间更新)

  十年程序员,呆过央企外企私企,做过前端后端架构。分享vue、Java等前后端技术和架构

  
本文在前文的基础上集成 MyBatisPlus,并创建数据库表,实现一个实体简单的 CRUD 接口。 MyBatis Plus 在 MyBatis 做了增强,内置了通用的 Mapper,同时也有代码生成器,简化单表的开发工作。

  1 准备数据库

  1.1 IDEA 配置数据库

  可以在 IDEA 中配置数据库,也可以使用 Navicat、DataGrip 等软件连接数据库。这里简单说说使用 IDEA 连接数据库的步骤。

  1)点击右侧上方的 Database,在弹出的 Database面板上,点击左上角加号图标,依次选择 Data Source -- MySQL

  2)在弹出的窗口中填写 host、port、User、Password,下载MySQL驱动后,点击 Test Connection,测试连接成功后,点击OK即可。

  1.2 创建数据库

  执行如下建库语句:

  

create database `hero_springboot_demo`

 

   default character set utf8mb4 collate utf8mb4_general_ci;

  

 

  1.3 创建表结构

  执行如下建表语句:

  

create table computer

 

   id bigint auto_increment,

   size decimal(4, 1) comment 尺寸,

   operation varchar(32) comment 操作系统,

   year varchar(4) comment 年份,

   primary key (id)

  ) comment 电脑;

  

 

  1.4 初始化数据

  

insert into computer(size, operation, year)

 

  values (16, MacOS, 2022),

   (14, MacOS, 2022),

   (15.6, MacOS, 2018),

   (13.3, MacOS, 2018),

   (15.6, MacOS, 2016),

   (13.3, MacOS, 2016),

   (14, Windows 10, 2022),

   (13, Windows 10, 2020),

   (11, Windows 10, 2018),

   (14, Windows 8, 2022),

   (13, Windows 8, 2020),

   (11, Windows 8, 2018);

  

 

  2 添加依赖

  需要添加如下依赖:

  mybatis-plus-boot-starter:Mybatis Plus 与 Spring Boot 整合所需;

  mysql-connector-java: MySQL 驱动;

  lombok:可选,简化 Getter、Setter、构造注入等,简化代码。

  在 properties 中定义 mybatis-plus 版本号:

  

 !-- MyBatis Plus 版本 -- 

 

   mybatis-plus.version 3.5.2 /mybatis-plus.version

  

 

  添加依赖:

  

 dependency 

 

   groupId mysql /groupId

   artifactId mysql-connector-java /artifactId

   /dependency

   dependency

   groupId com.baomidou /groupId

   artifactId mybatis-plus-boot-starter /artifactId

   version ${mybatis-plus.version} /version

   /dependency

   dependency

   groupId org.projectlombok /groupId

   artifactId lombok /artifactId

   scope provided /scope

   /dependency

  

 

  3 代码生成器

  MyBatis Plus 提供了代码生成器。在真实的开发中,通常会独立一个工程来生成相关代码,在这里的demo就直接通过单元测试的方式进行了。

  3.1 添加代码生成器依赖

  代码生成器的依赖为 mybatis-plus-generator,该依赖内部不含模板引擎,需要手动添加模板引擎的依赖,这里使用 freemarker。由于采用单元测试的方式生成代码,还需添加 junit。这三个 dependecy scope 都采用 test 即可。

  

 properties 

 

   mybatis-plus-generator.version 3.5.3 /mybatis-plus-generator.version

   /properties

  

 

  dependecies 中:

  

 dependency 

 

   groupId com.baomidou /groupId

   artifactId mybatis-plus-generator /artifactId

   version ${mybatis-plus-generator.version} /version

   scope test /scope

   /dependency

   dependency

   groupId org.freemarker /groupId

   artifactId freemarker /artifactId

   scope test /scope

   /dependency

   dependency

   groupId junit /groupId

   artifactId junit /artifactId

   scope test /scope

   /dependency

  

 

  3.2 编写单元测试

  在 src/test/java 下新建类:com.yygnb.demo.MyBatisPlusGeneratorTest,使用官方提供的新版方式进行代码生成的编写:

  

@Test

 

  public void testGenerate() {

   String url = "jdbc:mysql://localhost:3306/hero_springboot_demo?useUnicode=true characterEncoding=utf8 useSSL=true";

   String username = "root";

   String password = "Mysql.123";

   String author = "hero-yyg";

   String outputDir = "/Users/hero/temp-code";

   String parentPackage = "com.yygnb.demo";

   String moduleName = null;

   String outputFileXml = "/Users/hero/temp-code/xml";

   FastAutoGenerator.create(url, username, password)

   .globalConfig(builder - {

   builder.author(author) // 设置作者

   .outputDir(outputDir); // 指定输出目录

   .packageConfig(builder - {

   builder.parent(parentPackage) // 设置父包名

   .moduleName(moduleName) // 设置父包模块名

   .pathInfo(Collections.singletonMap(OutputFile.xml, outputFileXml)); // 设置mapperXml生成路径

   .strategyConfig(builder - {

   builder.addInclude("computer"); // 设置需要生成的表名

  // .addTablePrefix("t_", "c_"); // 设置过滤表前缀

   .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板

   .execute();

  

 

  注意修改方法开始的变量定义,包括 JDBC url、username、password、生成的代码的输出目录,生成的mapper 的输出目录。修改后执行单元测试,在指定的目录 /Users/hero/temp-code下可以看到生成的 controller、service、entity、mapper、xml。

  4 代码编写

  4.1 实体类

  将生成的实体类 Computer 复制到 com.yygnb.demo.entity中,生成的代码包括很多 Getter/Setter 等,可使用 前面引入的 lombok进行修改:

  

@Data

 

  @NoArgsConstructor

  @AllArgsConstructor

  @Builder

  public class Computer implements Serializable {

   private static final long serialVersionUID = 1L;

   @TableId(value = "id", type = IdType.AUTO)

   private Long id;

   * 尺寸

   private BigDecimal size;

   * 操作系统

   private String operation;

   * 年份

   private String year;

  

 

  4.2 mapper 和 service

  将生成的 mapper 拷贝到 src/main/java 中 com.yygnb.demo.mapper.ComputerMapper

  将生成的 service 目录整个拷贝到 com.yygnb.demo中

  将生成的 xml/ComputerMapper.xml 复制到 src/main/resources/mapper 下

  4.3 编写controller

  编写接口 com.yygnb.demo.controller.ComputerController:

  

package com.yygnb.demo.controller;

 

  import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

  import com.yygnb.demo.entity.Computer;

  import com.yygnb.demo.service.IComputerService;

  import lombok.RequiredArgsConstructor;

  import org.springframework.web.bind.annotation.*;

  @RequiredArgsConstructor

  @RestController

  @RequestMapping("/computer")

  public class ComputerController {

   private final IComputerService computerService;

   @GetMapping("/{id}")

   public Computer findById(@PathVariable Long id) {

   return this.computerService.getById(id);

   @GetMapping("/find-page/{page}/{size}")

   public Page Computer findPage(@PathVariable Integer page, @PathVariable Integer size) {

   return this.computerService.page(new Page (page, size));

   @PostMapping()

   public Computer save(@RequestBody Computer computer) {

   computer.setId(null);

   this.computerService.save(computer);

   return computer;

   @PutMapping("/{id}")

   public Computer update(@PathVariable Long id, @RequestBody Computer computer) {

   computer.setId(id);

   this.computerService.updateById(computer);

   return computer;

   @DeleteMapping("/{id}")

   public void delete(@PathVariable Long id) {

   this.computerService.removeById(id);

  

 

  上面包含了五个接口:

  

1. 根据id查询(get)

 

  2. 分页查询(get)

  3. 新增(post)

  4. 根据id修改(put)

  5. 根据id删除(delete)

  

 

  4.4 配置分页拦截器

  由于上面使用到分页查询,需要配置 MyBatis Plus 中的 Interceptor。创建类: com.yygnb.demo.config.MyBatisPlusConfig:

  

@Configuration

 

  public class MyBatisPlusConfig {

   @Bean

   public MybatisPlusInterceptor mybatisPlusInterceptor(){

   MybatisPlusInterceptor interceptor=new MybatisPlusInterceptor();

   interceptor.addInnerInterceptor(new PaginationInnerInterceptor());

   return interceptor;

  

 

  5 配置 MyBatis Plus

  5.1 application.yml

  在application.yml 配置数据源和 MyBatis Plus:

  

spring:

 

   datasource:

   driver-class-name: com.mysql.cj.jdbc.Driver

   url: jdbc:mysql://127.0.0.1:3306/hero_springboot_demo?useUnicode=true characterEncoding=utf8 useSSL=true

   username: root

   password: Mysql.123

  # mybatis 日志

  mybatis-plus:

   configuration:

   log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

  

 

  5.2 DemoApplication

  在启动类 DemoApplication下配置 Mapper 扫描路径:

  

@MapperScan("com.yygnb.demo.mapper")

 

  @SpringBootApplication

  public class DemoApplication {

   public static void main(String[] args) {

   SpringApplication.run(DemoApplication.class, args);

  

 

  6 测试运行

  至此,整合MyBatisPlus就完成了,启动服务,分别测试五个接口。由于还没有整合接口文档,可以先在 postman 或其他工具中测试。postman 使用的人较多,也比较简单。这里我就采用 IDEA 内置的 HTTP Client 进行测试。

  点击顶部 "Tools" -- "HTTP Client" -- "Create request in HTTP Client",会打开“rest-api.http”,在该界面可以编写请求。点击右上角的 "Add request" 可添加新请求。 多个请求之间,需要使用 ### 分隔。点击请求左侧的绿色三角便可执行请求。

  

POST http://localhost:9099/computer

 

  Content-Type: application/json

   "id": "",

   "size": "18",

   "operation": "Linux",

   "year": "2023"

  PUT http://localhost:9099/computer/13

  Content-Type: application/json

   "id": "",

   "size": "0",

   "operation": "Linux",

   "year": "2013"

  DELETE http://localhost:9099/computer/13

  GET http://localhost:9099/computer/13

  GET http://localhost:9099/computer/find-page/2/10

  

 

  虽然集成 MyBatis Plus 实现了增删改查接口,但上面的代码还存在很多问题:

  数据库的版本管理

  接口的参数校验和全局异常处理

  数据库连接池信息监控

  多环境配置

  服务运行状态监控等

  上述问题都会在后续的文章中逐步完善demo。

  今日优雅哥(youyacoder)学习结束,期待关注留言分享~~

  以上就是SpringBoot 如何集成 MyBatisPlus(梦到自己不停的找东西)的详细内容,想要了解更多 SpringBoot 如何集成 MyBatisPlus的内容,请持续关注盛行IT软件开发工作室。

郑重声明:本文由网友发布,不代表盛行IT的观点,版权归原作者所有,仅为传播更多信息之目的,如有侵权请联系,我们将第一时间修改或删除,多谢。

留言与评论(共有 条评论)
   
验证码: