SpringBoot整合MybatisPlus的教程詳解
Mybatis-Plus(簡(jiǎn)稱MP)是一個(gè) Mybatis 的增強(qiáng)工具,在 Mybatis 的基礎(chǔ)上只做增強(qiáng)不做改變,為簡(jiǎn)化開發(fā)、提高效率而生。
它已經(jīng)封裝好了一些crud方法,對(duì)于非常常見(jiàn)的一些sql我們不用寫xml了,直接調(diào)用這些方法就行,但它也是支持我們自己手動(dòng)寫xml。
幫我們擺脫了用mybatis需要寫大量的xml文件的麻煩,非常安逸哦
用過(guò)就不想用其他了,太舒服了
好了,我們開始整合整合

新建一個(gè)SpringBoot的工程

這里是我整合完一個(gè)最終的結(jié)構(gòu),可以參考一下
<?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>
引入相關(guān)的jar包

可以看到我這邊策略也有引入,它與mybatis一樣,也有對(duì)應(yīng)生成代碼的策略,我們直接用這個(gè)來(lái)幫我們把代碼生成就好
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 二級(jí)緩存
gc.setEnableCache(false);
// XML ResultMap
gc.setBaseResultMap(true);
// XML columList
gc.setBaseColumnList(false);
// gc.setSwagger2(true); 實(shí)體屬性 Swagger2 注解
mpg.setGlobalConfig(gc);
// 數(shù)據(jù)源配置
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() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
// String templatePath = "/templates/mapper.xml.vm";
// 自定義輸出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定義配置會(huì)被優(yōu)先輸出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定義輸出文件名 , 如果你 Entity 設(shè)置了前后綴、此處注意 xml 的名稱會(huì)跟著發(fā)生變化??!
return projectPath + "/src/main/resources/mappers/"
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
/*
cfg.setFileCreate(new IFileCreate() {
@Override
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
// 判斷自定義文件夾是否需要?jiǎng)?chuàng)建
checkDir("調(diào)用默認(rèn)方法創(chuàng)建的目錄");
return false;
}
});
*/
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定義輸出模板
//指定自定義模板路徑,注意不要帶上.ftl/.vm, 會(huì)根據(jù)使用的模板引擎自動(dòng)識(shí)別
// 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();
}
}
我有一個(gè)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;
我是直接針對(duì)它執(zhí)行策略的,

這幾個(gè)文件都是策略生成的,我沒(méi)有去動(dòng)過(guò)
package com.zkb.conf;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 配置分頁(yè)插件
*
*/
@Configuration
public class MybatisPlusConfig {
/**
* 分頁(yè)插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
server: port: 8081 servlet: context-path: / spring: datasource: # mysql5.x 配置,高版本需要加useSSL=false #url: jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false # mysql8.0 需要加&useSSL=false&serverTimezone=UTC url: jdbc:mysql://localhost:3306/900?zeroDateTimeBehavior=convertToNull&characterEncoding=utf8&useSSL=false&serverTimezone=UTC username: root password: baishou888 # mysql8.0 驅(qū)動(dòng) driver-class-name: com.mysql.cj.jdbc.Driver # mysql5.x 驅(qū)動(dòng) #driver-class-name: com.mysql.jdbc.Driver debug: false #Druid# name: test type: com.alibaba.druid.pool.DruidDataSource filters: stat maxActive: 20 initialSize: 1 maxWait: 60000 minIdle: 1 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: select 'x' testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true maxOpenPreparedStatements: 20 jackson: date-format: yyyy-MM-dd HH:mm:ss time-zone: GMT+8 mybatis-plus: configuration: map-underscore-to-camel-case: true auto-mapping-behavior: full log-impl: org.apache.ibatis.logging.stdout.StdOutImpl mapper-locations: classpath*:mapper/**/*Mapper.xml global-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 {
@Autowired
private UserService userService;
@GetMapping("/getUser")
public User getUser(){
return userService.getById(1231);
}
}
寫了一個(gè)get方法來(lái)測(cè)試自己是否與mybatis-plus整合成功,所以直接調(diào)用了mybatis-plus內(nèi)置的方法
當(dāng)然數(shù)據(jù)庫(kù)我自己手動(dòng)寫了一個(gè)id為1231的數(shù)據(jù)

可以看到整合成功了,對(duì)吧,真的是超級(jí)簡(jiǎn)單
點(diǎn)擊此處demo下載,需要自取
到此這篇關(guān)于SpringBoot整合MybatisPlus的文章就介紹到這了,更多相關(guān)SpringBoot整合MybatisPlus內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- springboot集成mybatisplus實(shí)例詳解
- SpringBoot整合MybatisPlus的簡(jiǎn)單教程實(shí)現(xiàn)(簡(jiǎn)單整合)
- SpringBoot集成MybatisPlus報(bào)錯(cuò)的解決方案
- SpringBoot整合MybatisPlus的基本應(yīng)用詳解
- springboot集成mybatisplus的方法
- 從零搭建SpringBoot+MyBatisPlus快速開發(fā)腳手架
- SpringBoot中引入MyBatisPlus的常規(guī)操作
- SpringBoot3.0集成MybatisPlus的實(shí)現(xiàn)方法
相關(guān)文章
Security框架:如何使用CorsFilter解決前端跨域請(qǐng)求問(wèn)題
這篇文章主要介紹了Security框架:如何使用CorsFilter解決前端跨域請(qǐng)求問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11
java8 如何實(shí)現(xiàn)分組計(jì)算數(shù)量和計(jì)算總數(shù)
這篇文章主要介紹了java8 如何實(shí)現(xiàn)分組計(jì)算數(shù)量和計(jì)算總數(shù)的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07
spring基于注解配置實(shí)現(xiàn)事務(wù)控制操作
這篇文章主要介紹了spring基于注解配置實(shí)現(xiàn)事務(wù)控制操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09
Spring實(shí)戰(zhàn)之依賴關(guān)系注入之后的行為示例
這篇文章主要介紹了Spring實(shí)戰(zhàn)之依賴關(guān)系注入之后的行為,結(jié)合實(shí)例形式分析了Spring依賴關(guān)系注入之后的行為實(shí)現(xiàn)與使用相關(guān)操作技巧,需要的朋友可以參考下2019-11-11
解析SpringBoot整合SpringDataRedis的過(guò)程
這篇文章主要介紹了SpringBoot整合SpringDataRedis的過(guò)程,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-06-06
java EasyExcel實(shí)現(xiàn)動(dòng)態(tài)列解析和存表
這篇文章主要為大家介紹了java EasyExcel實(shí)現(xiàn)動(dòng)態(tài)列解析和存表示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06

