SpringBoot整合MyBatis-Plus

使用過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方法,在控制臺中輸入要生成的表的表名,如下圖


image.png

執(zhí)行后可以清楚的看到自動創(chuàng)建了controller蜗元,entity或渤,service,mapper等新包奕扣,并且生成了對應(yīng)的java代碼薪鹦。


image.png

通過圖片可以清楚的看出生成了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]
image.png

由圖可知已經(jīng)查出了第一頁的10條數(shù)據(jù)寻馏。
好了到現(xiàn)在MyBatis-Plus的基本增刪改查棋弥,分頁操作就完成了,MyBatis-plus的更多使用就待你自己慢慢深入發(fā)掘了诚欠。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末顽染,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子轰绵,更是在濱河造成了極大的恐慌粉寞,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,826評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件左腔,死亡現(xiàn)場離奇詭異唧垦,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)液样,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,968評論 3 395
  • 文/潘曉璐 我一進(jìn)店門振亮,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人鞭莽,你說我怎么就攤上這事坊秸。” “怎么了澎怒?”我有些...
    開封第一講書人閱讀 164,234評論 0 354
  • 文/不壞的土叔 我叫張陵褒搔,是天一觀的道長。 經(jīng)常有香客問我,道長站超,這世上最難降的妖魔是什么荸恕? 我笑而不...
    開封第一講書人閱讀 58,562評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮死相,結(jié)果婚禮上融求,老公的妹妹穿的比我還像新娘。我一直安慰自己算撮,他們只是感情好生宛,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,611評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著肮柜,像睡著了一般陷舅。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上审洞,一...
    開封第一講書人閱讀 51,482評論 1 302
  • 那天莱睁,我揣著相機(jī)與錄音,去河邊找鬼芒澜。 笑死仰剿,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的痴晦。 我是一名探鬼主播南吮,決...
    沈念sama閱讀 40,271評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼誊酌!你這毒婦竟也來了部凑?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,166評論 0 276
  • 序言:老撾萬榮一對情侶失蹤碧浊,失蹤者是張志新(化名)和其女友劉穎涂邀,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體箱锐,經(jīng)...
    沈念sama閱讀 45,608評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡必孤,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,814評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了瑞躺。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片敷搪。...
    茶點(diǎn)故事閱讀 39,926評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖幢哨,靈堂內(nèi)的尸體忽然破棺而出赡勘,到底是詐尸還是另有隱情,我是刑警寧澤捞镰,帶...
    沈念sama閱讀 35,644評論 5 346
  • 正文 年R本政府宣布闸与,位于F島的核電站毙替,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏践樱。R本人自食惡果不足惜厂画,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,249評論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望拷邢。 院中可真熱鬧袱院,春花似錦、人聲如沸瞭稼。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,866評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽环肘。三九已至欲虚,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間悔雹,已是汗流浹背复哆。 一陣腳步聲響...
    開封第一講書人閱讀 32,991評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留腌零,地道東北人梯找。 一個月前我還...
    沈念sama閱讀 48,063評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像莱没,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子酷鸦,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,871評論 2 354