Springboot是當(dāng)下非常熱門,備受開發(fā)者青睞的一門技術(shù)框架。開發(fā)Springboot項(xiàng)目少不了要和數(shù)據(jù)庫交互,而Mybatis作為一款非常優(yōu)秀的持久層框架,經(jīng)常整合在Springboot項(xiàng)目中。下面,就和大家分享關(guān)于在Springboot項(xiàng)目中如何通過整合Mybatis以及Mybatis-plus來實(shí)現(xiàn)數(shù)據(jù)庫訪問功能。
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ù)庫連接池-->
<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>
<!--測試-->
<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)生成對應(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("請輸入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("請輸入正確的" + 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ù)庫表字段類型轉(zhuǎn)換【可選】
@Override
public IColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) {
System.out.println("轉(zhuǎn)換類型:" + fieldType);
// 注意??!processTypeConvert 存在默認(rèn)類型轉(zhuǎn)換,如果不是你要的效果請自定義返回、非如下直接返回。
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è)英文逗號分割").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ù)庫及表
創(chuàng)表語句
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 測試代碼生成器
執(zhí)行CodeGenerator類中的main方法
執(zhí)行代碼生成器之后的結(jié)果
3. 添加分頁配置
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 分頁插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
return paginationInterceptor;
}
}
4. 測試訪問接口從數(shù)據(jù)庫中獲取數(shù)據(jù)(帶分頁)
4.1 數(shù)據(jù)庫中添加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)前頁
* @param pageSize 每頁顯示的記錄數(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工具測試分頁
先測試第一頁每頁顯示3條記錄
查看第二頁的數(shù)據(jù)
到這里,本篇關(guān)于Springboot通過整合Mybatis和Mybatis-plus來實(shí)現(xiàn)數(shù)據(jù)庫訪問功能的文章就介紹結(jié)束了,如果您想要了解更多關(guān)于Springboot中數(shù)據(jù)庫的詳細(xì)內(nèi)容,可以多多關(guān)注W3Cschool相關(guān)內(nèi)容的文章。