SpringBoot快速整合Mybatis、MybatisPlus(代碼生成器)實(shí)現(xiàn)數(shù)據(jù)庫(kù)訪問功能
1. 創(chuàng)建SpringBoot項(xiàng)目

1.1 引入依賴
pom.xml
<?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 http://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.3.3.RELEASE</version>
</parent>
<groupId>com.gcl</groupId>
<artifactId>vue_day03_admin</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--spring-web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
<!--mybatis-plus代碼生成器-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
<!--mysql驅(qū)動(dòng)-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<!--數(shù)據(jù)庫(kù)連接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.21</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--測(cè)試-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--lang3工具類-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.10</version>
</dependency>
</dependencies>
<!-- maven插件,可以將應(yīng)用打包成一個(gè)可執(zhí)行的jar包;-->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
1.2 編寫配置文件
application.yml
server:
port: 8088
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:mysql://192.168.0.131:3306/vue_day03?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
username: root
password: Root@123456
mybatis-plus:
type-aliases-package: com.gcl.entity
configuration:
map-underscore-to-camel-case: true
use-generated-keys: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mapper-locations: classpath:com/gcl/mapper/*Mapper.xml
logging:
level:
com.demo.mapper: debug
2. 編寫MybatisPlus代碼生成工具類

2.1 編寫代碼生成工具類
CodeGenerator.java
package com.gcl.utils;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
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.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.IColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
// 執(zhí)行 main 方法控制臺(tái)輸入模塊表名回車自動(dòng)生成對(duì)應(yīng)項(xiàng)目目錄中
public class CodeGenerator {
/**
* <p>
* 讀取控制臺(tái)內(nèi)容
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("請(qǐng)輸入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("請(qǐng)輸入正確的" + tip + "!");
}
public static void main(String[] args) {
// 代碼生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/vue_day03_admin/src/main/java");
gc.setAuthor("gcl");
// 是否打開輸出目錄,默認(rèn)true
gc.setOpen(false);
// 開啟 ActiveRecord 模式,默認(rèn)false
gc.setActiveRecord(true);
// 是否覆蓋已有文件
gc.setFileOverride(true);
// XML 開啟 BaseResultMap
gc.setBaseResultMap(true);
// XML 開啟 baseColumnList
gc.setBaseColumnList(true);
// 自定義文件命名,注意 %s 會(huì)自動(dòng)填充表實(shí)體屬性!
// gc.setMapperName("%sDao");
// gc.setXmlName("%sMapper");
gc.setServiceName("%sService");
// gc.setServiceImplName("%sServiceDiy");
// gc.setControllerName("%sAction");
mpg.setGlobalConfig(gc);
// 數(shù)據(jù)源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL);
dsc.setUrl("jdbc:mysql://192.168.0.131:3306/vue_day03?useUnicode=true&useSSL=false&characterEncoding=utf8");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("Root@123456");
dsc.setTypeConvert(new MySqlTypeConvert(){
// 自定義數(shù)據(jù)庫(kù)表字段類型轉(zhuǎn)換【可選】
@Override
public IColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) {
System.out.println("轉(zhuǎn)換類型:" + fieldType);
// 注意??!processTypeConvert 存在默認(rèn)類型轉(zhuǎn)換,如果不是你要的效果請(qǐng)自定義返回、非如下直接返回。
return super.processTypeConvert(globalConfig, fieldType);
}
});
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
// com.demo.user
pc.setParent("com");
// pc.setModuleName("user");
pc.setModuleName(scanner("模塊名"));
mpg.setPackageInfo(pc);
// 自定義配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// TODO
}
};
mpg.setCfg(cfg);
// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 自定義輸出配置
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 + "/vue_day03_admin/src/main/resources/com/gcl/mapper"
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// 此處可以修改為您的表前綴
strategy.setTablePrefix(new String[] { "tb_", "tsys_","t_" });
// 表名生成策略
strategy.setNaming(NamingStrategy.underline_to_camel);
// 需要生成的表
strategy.setInclude(scanner("表名,多個(gè)英文逗號(hào)分割").split(","));
// strategy.setInclude(new String[] { "tb_user" });
strategy.setEntityBuilderModel(true);
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
2.2 創(chuàng)建數(shù)據(jù)庫(kù)及表
創(chuàng)表語(yǔ)句
CREATE TABLE `t_user` ( `id` int(60) NOT NULL AUTO_INCREMENT COMMENT '主鍵', `username` varchar(255) DEFAULT NULL COMMENT '姓名', `salary` double(7,2) DEFAULT NULL COMMENT '薪水', `age` int(11) DEFAULT NULL, `desc` varchar(255) DEFAULT NULL COMMENT '描述', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
2.3 測(cè)試代碼生成器
執(zhí)行CodeGenerator類中的main方法


執(zhí)行代碼生成器之后的結(jié)果

3. 添加分頁(yè)配置

MyBatisPlusConfig.java
package com.gcl.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @ClassName MyBatisPlusConfig
* @Description TODO
* @Author gcl
* @Date 2021-03-18 8:36
**/
@Configuration
public class MyBatisPlusConfig {
/**
* mybatis-plus 分頁(yè)插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
return paginationInterceptor;
}
}
4. 測(cè)試訪問接口從數(shù)據(jù)庫(kù)中獲取數(shù)據(jù)(帶分頁(yè))
4.1 數(shù)據(jù)庫(kù)中添加5條數(shù)據(jù)
INSERT INTO `vue_day03`.`t_user` (`id`, `username`, `salary`, `age`, `desc`) VALUES ('1', '張三', '2000.00', '23', '95年05月生');
INSERT INTO `vue_day03`.`t_user` (`id`, `username`, `salary`, `age`, `desc`) VALUES ('2', '李四', '3000.00', '24', '96年06年生');
INSERT INTO `vue_day03`.`t_user` (`id`, `username`, `salary`, `age`, `desc`) VALUES ('3', '王五', '4000.00', '25', '07年07年生');
INSERT INTO `vue_day03`.`t_user` (`id`, `username`, `salary`, `age`, `desc`) VALUES ('4', '趙六', '5000.00', '26', '08年08月生');
INSERT INTO `vue_day03`.`t_user` (`id`, `username`, `salary`, `age`, `desc`) VALUES ('5', '田七', '6000.00', '27', '09年09月生');
4.2 編寫查詢方法
package com.gcl.controller;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gcl.entity.User;
import com.gcl.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* <p>
* 前端控制器
* </p>
*
* @author gcl
* @since 2021-04-10
*/
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
/**
*
* @param pageNo 當(dāng)前頁(yè)
* @param pageSize 每頁(yè)顯示的記錄數(shù)
* @return
*/
@GetMapping
public List<User> findList(int pageNo,int pageSize){
//創(chuàng)建查詢條件封裝器
QueryWrapper<User> wrapper = new QueryWrapper<>();
Page<User> page = new Page<>(pageNo, pageSize);
IPage<User> iPage = userService.page(page, wrapper);
List<User> records = iPage.getRecords();
return records;
}
}
4.3 用postman工具測(cè)試分頁(yè)
先測(cè)試第一頁(yè)每頁(yè)顯示3條記錄

查看第二頁(yè)的數(shù)據(jù)

到此這篇關(guān)于SpringBoot快速整合Mybatis、MybatisPlus(代碼生成器)實(shí)現(xiàn)數(shù)據(jù)庫(kù)訪問功能的文章就介紹到這了,更多相關(guān)SpringBoot實(shí)現(xiàn)數(shù)據(jù)庫(kù)訪問內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring Cache相關(guān)知識(shí)總結(jié)
今天帶大家學(xué)習(xí)Spring的相關(guān)知識(shí),文中對(duì)Spring Cache作了非常詳細(xì)的介紹,對(duì)正在學(xué)習(xí)Java Spring的小伙伴們很有幫助,需要的朋友可以參考下2021-05-05
spring boot 如何優(yōu)雅關(guān)閉服務(wù)
這篇文章主要介紹了spring boot 如何優(yōu)雅關(guān)閉服務(wù),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-11-11
Springboot整合Shiro實(shí)現(xiàn)登錄與權(quán)限校驗(yàn)詳細(xì)解讀
本文給大家介紹Springboot整合Shiro的基本使用,Apache?Shiro是Java的一個(gè)安全框架,Shiro本身無法知道所持有令牌的用戶是否合法,我們將整合Shiro實(shí)現(xiàn)登錄與權(quán)限的驗(yàn)證2022-04-04
Java中Maven項(xiàng)目導(dǎo)出jar包配置的示例代碼
這篇文章主要介紹了Java中Maven項(xiàng)目導(dǎo)出jar包配置的示例代碼,需要的朋友可以參考下2018-11-11
mybatis執(zhí)行錯(cuò)誤但sql執(zhí)行正常問題
這篇文章主要介紹了mybatis執(zhí)行錯(cuò)誤但sql執(zhí)行正常問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-01-01

