使用過MyBatis的同學(xué)應(yīng)該都有過這種體會當(dāng)類里面要添加或刪減字段的時候苦囱,就要去修改Mapper.xml修改相對應(yīng)的SQL語句,這樣相對來說就有點(diǎn)麻煩容易出錯荤懂。今天給大家介紹一個工資MyBatis-Plus吃靠,plus是加強(qiáng)的意思,那MyBatis-Plus就是MyBatis的加強(qiáng)版渊抄,MyBatis—plus就解決了剛剛上面所說的問題尝胆,當(dāng)然他還有很多優(yōu)點(diǎn),今天就來學(xué)習(xí)一下SpringBoot如何整合MyBatis-Plus吧护桦。
MyBatis-Plus的優(yōu)點(diǎn)
1.無侵入含衔,強(qiáng)大的CRUD功能;
2.支持lambda形式調(diào)用二庵;
3.支持多種形式的自動生成主鍵贪染;
4.內(nèi)置代碼生成器,內(nèi)置分頁插件催享;
5.內(nèi)置全局?jǐn)r截插件杭隙,內(nèi)置sql注入剝離器;
對于 mybatis-plus 的使用因妙,可以參照官網(wǎng)http://mp.baomidou.com/
一寺渗、創(chuàng)建數(shù)據(jù)庫表
CREATE TABLE `tb_student` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`num` bigint(20) DEFAULT NULL,
`sex` varchar(255) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`native_place` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;
**二、創(chuàng)建SpringBoot項(xiàng)目
創(chuàng)建一個springboot項(xiàng)目 boketest
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 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.2.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.zyyqc</groupId>
<artifactId>boketest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<name>boketest</name>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</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>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.0</version>
</dependency>
<!-- mybatis plus 代碼生成器依賴 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.1.0</version>
</dependency>
<!-- 代碼生成器模板 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.編寫碼生成器
CodeGenerator.Class
package com.zyyqc.boketest.generator;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
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;
import java.util.Scanner;
public class CodeGenerator {
/**
* <p>
* 讀取控制臺內(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();
//獲取項(xiàng)目當(dāng)前所在文件夾位置
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("zhangxiansho");
gc.setOpen(false);
// service 命名方式
gc.setServiceName("%sService");
// service impl 命名方式
gc.setServiceImplName("%sServiceImpl");
// 自定義文件命名,注意 %s 會自動填充表實(shí)體屬性汁果!
gc.setMapperName("%sMapper");
gc.setXmlName("%sMapper");
gc.setFileOverride(true);
gc.setActiveRecord(true);
// XML 二級緩存
gc.setEnableCache(false);
// XML ResultMap
gc.setBaseResultMap(true);
// XML columList
gc.setBaseColumnList(false);
mpg.setGlobalConfig(gc);
// 數(shù)據(jù)源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://127.0.0.1:3306/boke?useUnicode=true&useSSL=false&characterEncoding=utf-8");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.zyyqc.boketest");
pc.setEntity("entity");
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<>();
// 自定義配置會被優(yōu)先輸出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定義輸出文件名 涡拘, 如果你 Entity 設(shè)置了前后綴、此處注意 xml 的名稱會跟著發(fā)生變化>莸隆鳄乏!
return projectPath + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定義輸出模板
//指定自定義模板路徑,注意不要帶上.ftl/.vm, 會根據(jù)使用的模板引擎自動識別
// 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("cn.com.bluemoon.demo.entity");
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// 公共父類
//strategy.setSuperControllerClass("cn.com.bluemoon.demo.controller");
// 寫于父類中的公共字段
//strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("表名棘利,多個英文逗號分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
//去掉數(shù)據(jù)庫表名的前綴橱野,這里我的數(shù)據(jù)庫中的表名加了“tb_”前綴
strategy.setTablePrefix("tb_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
代碼生成器中的一些基本配置比如作者名稱,包的路徑善玫,數(shù)據(jù)庫鏈接地址根據(jù)自己的實(shí)際情況進(jìn)行調(diào)整水援。
3.執(zhí)行代碼生成器
執(zhí)行代碼生成器中的main方法,在控制臺中輸入要生成的表的表名,如下圖
執(zhí)行后可以清楚的看到自動創(chuàng)建了controller蜗元,entity或渤,service,mapper等新包奕扣,并且生成了對應(yīng)的java代碼薪鹦。
通過圖片可以清楚的看出生成了tb_student和tb_excel_zip兩張表對應(yīng)的java類。
4.application.yml
spring:
#數(shù)據(jù)庫配置
datasource:
url: jdbc:mysql://127.0.0.1:3306/boke?useUnicode=true&useSSL=false&characterEncoding=utf-8
username: root
password: root
# 使用druid數(shù)據(jù)源
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
5.簡單的CRUD
剛剛已經(jīng)自動生成了大部分的java代碼了惯豆,這樣大大提高了我們的開發(fā)效率池磁,不僅如此MyBatis-Plus還封裝了大量的方法,下面就來試一下楷兽。
@RestController
@RequestMapping("/student")
public class StudentController {
@Resource
private StudentService studentService;
@PostMapping("/saveOrUpdate")
public String saveOrUpdate(@RequestBody Student student) {
boolean saveOrUpdate = true;
if (Objects.isNull(student.getId())) {
saveOrUpdate = studentService.save(student);
} else {
saveOrUpdate = studentService.updateById(student);
}
if (saveOrUpdate) {
return "保存成功!";
} else {
return "保存失敗!";
}
}
@PostMapping("/delete")
public String delete(Long id) {
boolean b = studentService.removeById(id);
if (b) {
return "刪除成功";
} else {
return "刪除失敗";
}
}
@PostMapping("/list")
public List<Student> list() {
List<Student> list = studentService.list();
return list;
}
}
上面所調(diào)用的save框仔,updateById,removeById拄养,list都是mybatis-plus封裝好的使用很方便的,還有很多方法大家可以自己去研究一下银舱。
6.分頁查詢
mybatis-plus內(nèi)置了分頁插件用起來也是很方便的首先需要添加一個配置類
@Configuration
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
return paginationInterceptor;
}
}
@PostMapping("/listBody")
public List<Student> list(@RequestBody StudentQuery query) {
Page<Student> page = studentService.queryPageList(query);
return page.getRecords();
}
@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
public class StudentQuery implements Serializable{
private static final long Serializable = 1L;
private int currentPage = 1;
private int pageSize = 10;
}
StudentQuery 類是分頁查詢的條件瘪匿,里面包含了要查詢的當(dāng)前頁currentPage和每一頁的數(shù)據(jù)量pageSize,默認(rèn)值是取第1頁每一頁10條數(shù)據(jù)。
接下來是service和mapper中的代碼
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {
@Resource
private StudentMapper studentMapper;
@Override
public Page<Student> queryPageList(StudentQuery query) {
Page<Student> page = new Page<>(query.getCurrentPage(), query.getPageSize());
LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<>();
List<Student> students = studentMapper.queryPageList(page,queryWrapper);
page.setRecords(students);
return page;
}
/**
* <p>
* Mapper 接口
* </p>
*
* @author zhangxiansho
* @since 2020-04-01
*/
public interface StudentMapper extends BaseMapper<Student> {
List<Student> queryPageList(Page<Student> page, @Param("queryWrapper") Wrapper<Student> queryWrapper);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zyyqc.boketest.mapper.StudentMapper">
<!-- 通用查詢映射結(jié)果 -->
<resultMap id="BaseResultMap" type="com.zyyqc.boketest.entity.Student">
<id column="id" property="id" />
<result column="name" property="name" />
<result column="num" property="num" />
<result column="sex" property="sex" />
<result column="age" property="age" />
<result column="native_place" property="nativePlace" />
</resultMap>
<select id="queryPageList" resultType="com.zyyqc.boketest.entity.Student">
select * from tb_student
<where>
${queryWrapper.sqlSegment}
</where>
</mapper>
接下來做個單元測試看一下結(jié)果
@Test
void queryPageList() {
Page<Student> page = studentService.queryPageList(new StudentQuery());
if (CollectionUtils.isNotEmpty(page.getRecords())) {
page.getRecords().forEach(System.out::println);
}
}
![image.png]由圖可知已經(jīng)查出了第一頁的10條數(shù)據(jù)寻馏。
好了到現(xiàn)在MyBatis-Plus的基本增刪改查棋弥,分頁操作就完成了,MyBatis-plus的更多使用就待你自己慢慢深入發(fā)掘了诚欠。