Mybatis-Plus(简称MP)是一个 Mybatis 的增强工具,在 Mybatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

它已经封装好了一些crud方法,对于非常常见的一些sql我们不用写xml了,直接调用这些方法就行,但它也是支持我们自己手动写xml。

帮我们摆脱了用mybatis需要写大量的xml文件的麻烦,非常安逸哦

用过就不想用其他了,太舒服了

好了,我们开始整合整合

新建一个SpringBoot的工程

这里是我整合完一个最终的结构,可以参考一下

<?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.4.0</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.zkb</groupId><artifactId>spring-boot-mybatisplus</artifactId><version>0.0.1-SNAPSHOT</version><name>spring-boot-mybatisplus</name><description>Demo project for Spring Boot</description><properties><java.version>11</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><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><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.18</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.21</version></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.3.2</version></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.3.2</version><scope>test</scope></dependency><dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId><version>2.3.30</version><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

引入相关的jar包

可以看到我这边策略也有引入,它与mybatis一样,也有对应生成代码的策略,我们直接用这个来帮我们把代码生成就好

package com.example.mybatisplus;import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;import java.util.ArrayList;
import java.util.List;public class MysqlGenerator {public static void main(String[] args) {// 代码生成器AutoGenerator mpg = new AutoGenerator();// 全局配置GlobalConfig gc = new GlobalConfig();String projectPath = System.getProperty("user.dir");gc.setOutputDir(projectPath + "/src/main/java");gc.setAuthor("zkb");gc.setOpen(false);// service 命名方式gc.setServiceName("%sService");// service impl 命名方式gc.setServiceImplName("%sServiceImpl");gc.setMapperName("%sMapper");gc.setXmlName("%sMapper");gc.setFileOverride(true);gc.setActiveRecord(true);// XML 二级缓存gc.setEnableCache(false);// XML ResultMapgc.setBaseResultMap(true);// XML columListgc.setBaseColumnList(false);// gc.setSwagger2(true); 实体属性 Swagger2 注解mpg.setGlobalConfig(gc);// 数据源配置DataSourceConfig dsc = new DataSourceConfig();dsc.setUrl("jdbc:mysql://localhost:3306/900?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false");// dsc.setSchemaName("public");dsc.setDriverName("com.mysql.cj.jdbc.Driver");dsc.setUsername("root");dsc.setPassword("baishou888");mpg.setDataSource(dsc);// 包配置PackageConfig pc = new PackageConfig();pc.setParent("com.zkb");pc.setEntity("model");pc.setService("service");pc.setServiceImpl("service.impl");mpg.setPackageInfo(pc);// 自定义配置InjectionConfig cfg = new InjectionConfig() {@Overridepublic void initMap() {// to do nothing}};// 如果模板引擎是 freemarkerString templatePath = "/templates/mapper.xml.ftl";// 如果模板引擎是 velocity// String templatePath = "/templates/mapper.xml.vm";// 自定义输出配置List<FileOutConfig> focList = new ArrayList<>();// 自定义配置会被优先输出focList.add(new FileOutConfig(templatePath) {@Overridepublic String outputFile(TableInfo tableInfo) {// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!return projectPath + "/src/main/resources/mappers/"+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;}});/*cfg.setFileCreate(new IFileCreate() {@Overridepublic boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {// 判断自定义文件夹是否需要创建checkDir("调用默认方法创建的目录");return false;}});*/cfg.setFileOutConfigList(focList);mpg.setCfg(cfg);// 配置模板TemplateConfig templateConfig = new TemplateConfig();// 配置自定义输出模板//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别// templateConfig.setEntity("templates/entity2.java");// templateConfig.setService();// templateConfig.setController();templateConfig.setXml(null);mpg.setTemplate(templateConfig);// 策略配置StrategyConfig strategy = new StrategyConfig();strategy.setNaming(NamingStrategy.underline_to_camel);strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//        strategy.setSuperEntityClass("com.baomidou.ant.common.BaseEntity");strategy.setEntityLombokModel(true);strategy.setRestControllerStyle(true);// 公共父类
//        strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController");// 写于父类中的公共字段
//        strategy.setSuperEntityColumns("id");strategy.setInclude(new String[]{"t_user"});strategy.setControllerMappingHyphenStyle(true);strategy.setTablePrefix("t" + "_");mpg.setStrategy(strategy);mpg.setTemplateEngine(new FreemarkerTemplateEngine());mpg.execute();}
}

我有一个t_user的表

CREATE TABLE `t_user` (`id` bigint NOT NULL AUTO_INCREMENT,`username` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,`password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,`nickname` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,`gender` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,`telephone` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,`registerdate` datetime NOT NULL,`address` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,`addTime` timestamp NOT NULL DEFAULT '2015-09-15 00:00:00',`updateTime` timestamp NOT NULL DEFAULT '2015-09-15 00:00:00' ON UPDATE CURRENT_TIMESTAMP,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=44138653810545248 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

我是直接针对它执行策略的,

这几个文件都是策略生成的,我没有去动过

package com.zkb.conf;import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/*** 配置分页插件**/
@Configuration
public class MybatisPlusConfig {/*** 分页插件*/@Beanpublic PaginationInterceptor paginationInterceptor() {return new PaginationInterceptor();}
}
server:port: 8081servlet:context-path: /spring:datasource:# mysql5.x 配置,高版本需要加useSSL=false#url: jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false# mysql8.0 需要加&useSSL=false&serverTimezone=UTCurl: jdbc:mysql://localhost:3306/900?zeroDateTimeBehavior=convertToNull&characterEncoding=utf8&useSSL=false&serverTimezone=UTCusername: rootpassword: baishou888# mysql8.0 驱动driver-class-name: com.mysql.cj.jdbc.Driver# mysql5.x 驱动#driver-class-name: com.mysql.jdbc.Driverdebug: false#Druid#name: testtype: com.alibaba.druid.pool.DruidDataSourcefilters: statmaxActive: 20initialSize: 1maxWait: 60000minIdle: 1timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: select 'x'testWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: truemaxOpenPreparedStatements: 20jackson:date-format: yyyy-MM-dd HH:mm:sstime-zone: GMT+8mybatis-plus:configuration:map-underscore-to-camel-case: trueauto-mapping-behavior: fulllog-impl: org.apache.ibatis.logging.stdout.StdOutImplmapper-locations: classpath*:mapper/**/*Mapper.xmlglobal-config:# 逻辑删除配置db-config:# 删除前logic-not-delete-value: 1# 删除后logic-delete-value: 0
package com.zkb;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
@MapperScan("com.zkb.mapper")
public class SpringBootMybatisplusApplication {public static void main(String[] args) {SpringApplication.run(SpringBootMybatisplusApplication.class, args);}}
@MapperScan("com.zkb.mapper")一定是扫描到自己mapper的接口类
package com.zkb.controller;import com.zkb.model.User;
import com.zkb.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;/*** <p>*  前端控制器* </p>** @author zkb* @since 2020-11-23*/
@RestController
@RequestMapping("/user")
public class UserController {@Autowiredprivate UserService userService;@GetMapping("/getUser")public User getUser(){return userService.getById(1231);}}

写了一个get方法来测试自己是否与mybatis-plus整合成功,所以直接调用了mybatis-plus内置的方法

当然数据库我自己手动写了一个id为1231的数据

可以看到整合成功了,对吧,真的是超级简单

https://download.csdn.net/download/qq_14926283/13183105 demo地址,需要自取

SpringBoot整合MybatisPlus相关推荐

  1. SpringBoot整合MyBatis-Plus分页查询

    在整合mybatis-plus时可以先参考官网:快速开始 一.引入依赖 <dependency><groupId>org.springframework.boot</gr ...

  2. SpringBoot整合Mybatis-plus实现增删查改

    今天给大家分享一下SpringBoot整合Mybatis-plus的增删查改案例. pom.xml <?xml version="1.0" encoding="UT ...

  3. 实践丨SpringBoot整合Mybatis-Plus项目存在Mapper时报错

    本文分享自华为云社区<SpringBoot整合MybatisPlus项目存在Mapper时运行报错的问题分析与修复>,作者:攻城狮Chova . 异常信息 在SpringBoot运行测试M ...

  4. 超详细教程:SpringBoot整合MybatisPlus

    本文分享自华为云社区<SpringBoot整合MybatisPlus[超详细]>,原文作者:牛哄哄的柯南. 创建个SpringBoot项目 选生所需的依赖:== 我把application ...

  5. SpringBoot整合Mybatis-Plus

    这篇文章介绍一个SpringBoot整合Mybatis-Plus,提供一个小的Demo供大家参考. 已经很久没有写文章了,最近家里有点事刚刚处理完,顺便也趁机休息了一段时间.刚回到公司看了一下码云,发 ...

  6. SpringBoot整合Mybatis-Plus,代码生成器Generator以及Swagger(附源码、图文学习、Postman、ApiPost第三方工具的使用)

    目录 一.SpringBoot整合Mybatis-plus 1.引入依赖 2.创建数据库 3.整合代码生成器Generator 二.什么是Swagger2,有什么作用? 三.SpringBoot整合S ...

  7. 10-Java框架-SpringBoot整合MyBatis-Plus

    一.MyBatis-Plus介绍 官网 https://baomidou.com/ MyBatis-Plus(简称 MP)是一个 MyBatis的增强工具,在 MyBatis 的基础上只做增强不做改变 ...

  8. springboot整合mybatis-plus完整案例

    1.mybatis-plus,plus意思为插件,只在原来的基础上增强不做改变,只要进行简单的配置就可以对单表进行crud,还提供了强大的条件构造器wrapper以及代码生成器等.如下为springb ...

  9. springboot整合mybatisplus配置多数据源

    前言 业务中,有一个需求,需要定时将一个库的部分业务表的数据同步到另一个库中,由于在现有的项目中进行改造比较麻烦,因此索性使用springboot和mybatisplus完成一个多数据源的环境搭建 简 ...

  10. SpringBoot整合Mybatis-Plus连接Oracle数据库生成代码

    1.首先创建一个springboot项目(勾选数据库Driver驱动) 2.在pom中添加以下依赖 <?xml version="1.0" encoding="UT ...

最新文章

  1. django时间格式化加时区控制
  2. 一个简单可参考的API网关架构设计
  3. 开源Linux 3.3内核首次融合Android代码
  4. (转)Silverlight显示本地图片、Stream转Byte数组
  5. Android:JAVA使用HDF5存储
  6. SAP的软件是如何深刻影响着世界的?
  7. php代码加注释_怎么在php中添加注释
  8. 几种常见的基于Lucene的开源搜索解决方案对比
  9. 明解c语言练习答案,《明解C语言》练习题4-2的实现
  10. 磁碟机病毒***猖獗教你应对方法
  11. 安装kubernetes k8s v1.16.0 国内环境
  12. ORACLE RAC 11.2.0.4 一节点出现Suspending MMON slave action kewrmrfsa_ for 82800 seconds
  13. aqs clh java_并发编程——详解 AQS CLH 锁
  14. 微信开发MySQL篇(一)
  15. Gem5模拟器,详解官网教程Debugging gem5(四)
  16. bitbake hello world demo 实验
  17. 微服务架构这马丁富勒的论文
  18. 【腾讯Bugly干货分享】聊聊苹果的Bug - iOS 10 nano_free Crash
  19. 密码学—仿射密码实验报告
  20. maya多边形建模怎样做曲面_Maya的几种建模方法

热门文章

  1. 流年里写给30岁的自己
  2. Footprint:如何寻找有增长潜力的NFT项目?
  3. PowerShell 开启无线热点
  4. XML文件的操作--上
  5. CRM软件成功案例解析
  6. Turtle库学习--TurtleScreen/Screen 方法及对应函数
  7. CRMEB小程序商城v4.0二次开发对接集成阿里云短信
  8. Android 获取照相机图片或本地图片
  9. PCL笔记二:PCD解析;PCD读取;PCD与XYZ转换;
  10. Mysql 最全教程