MyBatisPlus入门学习

前言:在之前的博客中有讲过mybatis技术

mybatis入门博客链接

mybatis加强博客链接

mybatis高级博客链接

一、mybatisPlus简介

1、mybatisPlus概念

  • 简称 MP:是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
  • 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
  • 支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer2005、SQLServer 等多种数据库
  • 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、daomin,query, Model 、mapper.xml, Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用
  • 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
  • 内置 Sql 注入剥离器:支持 Sql 注入剥离,有效预防 Sql 注入攻击
  • 等等还有很多。。。

2、mybatisPlus结构

MyBatisPlus入门学习_第1张图片

二、mybatisPlus入门操作准备

在springboot中使用。
使用mybatisPlus,然后根据数据库中的表生成你想要的代码:
domain,query,mapper,mapper.xml,service,controller

1、项目结构搭建:创建一个父工程项目mp_parent,两个子模块mp_project和mp_generator

  • 子模块mp_generator:用于配置mp
  • 子模块mp_project:用于存放生成后的项目代码
    MyBatisPlus入门学习_第2张图片

2、在父工程的pom.xml中导入依赖

注意:springboot的版本控制依赖


    UTF-8
    UTF-8
    1.8
    2.0.5.RELEASE


    
        
            org.springframework.boot
            spring-boot-dependencies
            ${springboot.version}
            pom
            import
        
    

3、子模块mp_generator准备。(mp配置,生成代码)

(1)、在mp_generator的pom.xml中引入依赖

baomidou、模板引擎、MySQL数据库


    
    
        org.springframework.boot
        spring-boot-starter-web
    
    
        org.springframework.boot
        spring-boot-starter-test
    
    
    
        com.baomidou
        mybatis-plus-boot-starter
        2.2.0
    

    
    
        org.apache.velocity
        velocity-engine-core
        2.0
    
    
    
        mysql
        mysql-connector-java
    

(2)、在资源文件resources中创建properties配置文件。连接数据库配置

#此处为本项目src所在路径(代码生成器输出路径),注意一定是当前项目所在的目录哟
OutputDir=H:\\idea\\idea_workspace\\mp_parent\\mp_project\\src\\main\\java
#mapper.xml SQL映射文件目录
OutputDirXml=H:\\idea\\idea_workspace\\mp_parent\\mp_project\\src\\main\\resources

#我们生产代码要放的项目的地址:
OutputDirBase=H:\\idea\\idea_workspace\\mp_parent\\mp_project\\src\\main\\java
#设置作者
author=lyqtest
#自定义包路径
parent=cn.lyq.aigou.mp

#数据库连接信息
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///sell
jdbc.user=root
jdbc.pwd=123456

(3)、写生成代码的配置测试。

拷贝修改即可

package cn.lyq.aigou.mp;

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.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.util.*;

public class GenteratorCode {

    public static void main(String[] args) throws InterruptedException {
        //用来获取Mybatis-Plus.properties文件的配置信息
        final ResourceBundle rb = ResourceBundle.getBundle("mpconfig");
        AutoGenerator mpg = new AutoGenerator();
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(rb.getString("OutputDir"));
        //覆盖
        gc.setFileOverride(true);
        gc.setActiveRecord(true);// 开启 activeRecord 模式
        gc.setEnableCache(false);// XML 二级缓存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(false);// XML columList
        gc.setAuthor(rb.getString("author"));
        //生成代码运行后不弹出生成的文件路径盘符
        gc.setOpen(false);
        mpg.setGlobalConfig(gc);
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        //设置你数据库类型:
        dsc.setDbType(DbType.MYSQL);
        dsc.setTypeConvert(new MySqlTypeConvert());
        dsc.setDriverName(rb.getString("jdbc.driver"));
        dsc.setUsername(rb.getString("jdbc.user"));
        dsc.setPassword(rb.getString("jdbc.pwd"));
        dsc.setUrl(rb.getString("jdbc.url"));
        mpg.setDataSource(dsc);
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setTablePrefix(new String[] { "t_" });// 此处可以修改为您的表前缀
        strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
        strategy.setInclude(new String[]{"t_user"}); // 需要生成的表
        mpg.setStrategy(strategy);
        // 包配置
        PackageConfig pc = new PackageConfig();
        // parent:cn.itsource.aigou.mp
        pc.setParent(rb.getString("parent"));
        pc.setController("controller");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        pc.setEntity("domain");
        pc.setMapper("mapper");
        mpg.setPackageInfo(pc);

        // 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map map = new HashMap();
                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-rb");
                this.setMap(map);
            }
        };

        List focList = new ArrayList();

        // 调整 domain 生成目录演示
        focList.add(new FileOutConfig("/templates/entity.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return rb.getString("OutputDirBase")+ "/cn/lyq/aigou/mp/domain/" + tableInfo.getEntityName() + ".java";
            }
        });

        // 调整 xml 生成目录演示:本来mybatis的mapper.xml应该放到resources下:路径应该和Mapper.java的路径一致:
        focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return rb.getString("OutputDirXml")+ "/cn/lyq/aigou/mp/mapper/" + tableInfo.getEntityName() + "Mapper.xml";
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改,
        // 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称
        TemplateConfig tc = new TemplateConfig();
        tc.setService("/templates/service.java.vm");
        tc.setServiceImpl("/templates/serviceImpl.java.vm");
        tc.setEntity(null);
        tc.setMapper("/templates/mapper.java.vm");
        tc.setController(null);
        tc.setXml(null);
        // 如上任何一个模块如果设置 空 OR Null 将不生成该模块。
        mpg.setTemplate(tc);

        // 执行生成
        mpg.execute();
    }
}

(4)、运行上面的生成代码配置后。生成相应的代码

根据资源文件resources中创建properties配置文件中的生成代码的去处来生成代码。配置中生成到mp_project子模块中

4、子模块mp_project准备。(要运行的工程)

(1)、在pom.xml中引入依赖


    
    
        org.springframework.boot
        spring-boot-starter-web
    
    
        org.springframework.boot
        spring-boot-starter-test
    
    
    
        com.baomidou
        mybatis-plus-boot-starter
        2.2.0
    
    
    
        mysql
        mysql-connector-java
    

(2)、在资源文件resources中创建YAML配置,连接数据库

注意:别名配置,方便在mapper.xml中使用

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql:///sell
    username: root
    password: 123456
mybatis-plus:
  type-aliases-package: cn.lyq.aigou.mp.domain #设置别名

(3)、通过代码生成器生成的映射文件UserMapper.xml文件

通用查询映射结果:不用再写sql语句就可以完成CRUD操作
MyBatisPlus入门学习_第3张图片

(4)、生成的domain层省略了,不解释。

根据数据库中的表生成的

(5)、生成的接口mapper层

自动继承了一个BaseMapper。父类BaseMapper中有所有的CRUD方法

  • 生成的自己的mapper接口
    MyBatisPlus入门学习_第4张图片
  • 继承的父类接口mapper中的底层源码方法。只截图了一部分
    MyBatisPlus入门学习_第5张图片

(6)、生成的service层

  • service的接口:

生成后也是自动继承一个父类的service接口IService。粗略的看一下下面的截图(父接口IService中的部分源码方法)
MyBatisPlus入门学习_第6张图片

自己的service接口
MyBatisPlus入门学习_第7张图片

  • 生成的service实现类

继承了一个自动生成的service层实现类,并且实现了自己的service接口
MyBatisPlus入门学习_第8张图片

(7)、由于是springboot,所以要在aigou_project创建个启动类用于接下来的测试

注意:要开启mapper层的扫描注解

@SpringBootApplication
//开启mapper的扫描注解:mapper和xml都扫描了
@MapperScan(basePackages ="cn.lyq.aigou.mp.mapper")
public class MpApplication {
    public static void main(String[] args) {
        SpringApplication.run(MpApplication.class);
    }
}

三、mybatisPlus入门操作

上面的入门操作准备已经准备好的基础上

1、mybatisPlus的增加操作

注意不要忘了测试要用的注解。insert方法是生成代码时自动生成的,不是自己定义的
MyBatisPlus入门学习_第9张图片

2、mybatisPlus的查询一条数据操作

在这里插入图片描述

3、mybatisPlus的查询所有数据操作

MyBatisPlus入门学习_第10张图片

4、mybatisPlus查询数据库中存在的数据

MyBatisPlus入门学习_第11张图片

5、mybatisPlus删除数据操作

源码中有很多方法,这里就只用了根据id删除数据
MyBatisPlus入门学习_第12张图片

6、mybatisPlus更新数据方法

MyBatisPlus入门学习_第13张图片

7、以上都是使用的mybatisPlus中的自动生成的CRUD方法,现在试一下自己手动写方法操作数据库。

写一个查询一条数据的方法

(1)、先在映射文件mapper.xml中写相应的SQL语句

在这里插入图片描述

(2)、在mapper的接口中写相应的方法

MyBatisPlus入门学习_第14张图片

(3)、service层

  • service的接口层
    在这里插入图片描述
  • service的实现层
    MyBatisPlus入门学习_第15张图片

(4)、测试

在这里插入图片描述

8、mybatisPlus分页功能

(1)、先配置分页的插件。

创建个config配置文件包,里面写分页的配置类。拷贝过去修改。

//Spring boot方式
@EnableTransactionManagement
@Configuration
@MapperScan("cn.lyq.aigou.mp.mapper")
public class MybatisPlusConfig {

    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}

(2)、研究mybatisPlus的分页源码

mybatisPlus已经提供好了分页的功能,当然也有源码供参考。以下是部分的截图

MyBatisPlus入门学习_第16张图片

(3)、测试分页功能

MyBatisPlus入门学习_第17张图片

你可能感兴趣的:(MyBatisPlus)