Mybatis-plus文档学习实践

Mybatis-plus文档学习实践

版本说明

名称版本
springboot2.1.9
mybatis-plus3.4.0
JDK1.8
mysql5.7

本文主要是为了记录, 最好是结合官方文档一起学习, 一些具体的参数配置没有详细说明, 需要的可以去官方网站查看 ,文末附带地址

案例地址

案例地址

什么是mybatis-plus

MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

代码生成器

底层就是mybatis的逆向工程

需要引入pom

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.0</version>
        </dependency>
     <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.30</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

代码生成类 CodeGenerator

public class CodeGenerator {
    /**
     * <p>
     * 读取控制台内容
     * </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.isNotBlank(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")+"/mybatis-plus";
        //注意生成的路径位置
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("qiuwei");
        gc.setOpen(false);
        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://127.0.0.1:3306/plus?characterEncoding=utf-8&useSSL=true");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        mpg.setDataSource(dsc);
        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(scanner("模块名"));
        pc.setParent("com.qiuwei.mybatisplus");
        mpg.setPackageInfo(pc);
        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
                        + "/" + 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.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//        strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // 公共父类
//        strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
        // 写于父类中的公共字段
        strategy.setSuperEntityColumns("id");
        strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}

效果

在这里插入图片描述
输入对应的 模块名称和要生成代码的表

在这里插入图片描述

mybatis-plus快速入门

pom依赖

       <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.0</version>
        </dependency>

准备的数据表

create table user
(
    id    bigint auto_increment comment '主键ID'
        primary key,
    name  varchar(30)      null comment '姓名',
    age   int              null comment '年龄',
    email varchar(50)      null comment '邮箱',
    sex   int(1) default 1 null comment '性别 1男 2 女'
);
INSERT INTO user (id, name, age, email, sex) VALUES (1, 'Jone', 18, 'test1@baomidou.com', 1);
INSERT INTO user (id, name, age, email, sex) VALUES (2, 'Jack', 20, 'test2@baomidou.com', 1);
INSERT INTO user (id, name, age, email, sex) VALUES (3, 'Tom', 28, 'test3@baomidou.com', 1);
INSERT INTO user (id, name, age, email, sex) VALUES (4, 'Sandy', 21, 'test4@baomidou.com', 1);
INSERT INTO user (id, name, age, email, sex) VALUES (5, 'Billie', 24, 'test5@baomidou.com', 1);

mapper层的CRUD

application.yaml
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:p6spy:mysql://127.0.0.1:3306/plus?characterEncoding=utf-8&useSSL=true
    username: root
    password: 123456
 mybatis-plus:
 #注意核心文件和mapper映射文件路劲的扫描问题
  config-location: "classpath:mapper/mybatis-config.xml"
  mapper-locations: "classpath*:mapper/*/*Mapper.xml"   
mybatis-config.xml

主要是为了打印平台执行sql的日志 简单实例可以不配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <!-- 数据库连接超时时间 -->
        <setting name="defaultStatementTimeout" value="30000"/>
        <!-- 开启驼峰映射 -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
</configuration>
User
@Data
public class User  implements Serializable {
    private static final long serialVersionUID = 1L;
    //使用的是自增的配置 还有其他配置 需要的看官方文档这里不做具体说明
    @TableId(type = IdType.AUTO)
    private Long id;
    /**
     * 姓名
     */
    private String name;
    /**
     * 年龄
     */
    private Integer age;
    /**
     * 邮箱
     */
    private String email;
}
UserMapper
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
测试Test
 @Test
    public void save() {
        //插入
        User user = new User();
        user.setAge(18);
        user.setName("小红");
        user.setEmail("wcbc01110@126.com");
        userMapper.insert(user);
        //查询
        Long id = user.getId();
        User userInsert = this.userMapper.selectById(id);
        System.out.println(userInsert.toString());
        //更新
        user.setAge(27);
        user.setName("更新后的姓名");
        user.setEmail("qqqq@123.com");
        this.userMapper.updateById(user);
        System.out.println(user.toString());
        //删除
        this.userMapper.deleteById(id);
    }

结果
在这里插入图片描述

mybatis-plus对枚举的处理

mybatis-plus对于枚举的处理比较简单 有两种方式

User

private SexEnum sex;

SexEnum

第一种自定义

@Getter
public enum SexEnum {
    MAN(1, "男"),
    WOMEN(2, "女");
    @EnumValue
    @JsonValue
    private int code;
    private String msg;
    SexEnum(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }
    @Override
    public String toString() {
        return msg;
    }
}

第二种 使用mybatis-plus提供的

@Getter
public enum SexEnum implements IEnum<Integer> {
    MAN(1, "男"),
    WOMEN(2, "女");
    
    private int code;
    private String msg;
    SexEnum(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }
    /**
     * 主要是这个方法重写的谁 到时候封装到数据库的就是谁
     * @return
     */
    @Override
    public Integer getValue() {
        return this.code;
    }
}

本案例采用的是自定义的

配置扫描通用枚举

type-enums-package: com.qiuwei.mybatisplus.*.enums

application.yaml
mybatis-plus:
 # 添加通用枚举扫描路劲
  type-enums-package: com.qiuwei.mybatisplus.*.enums
 #  注意核心文件和mapper映射文件路劲的扫描问题
  config-location: "classpath:mapper/mybatis-config.xml"
  mapper-locations: "classpath*:mapper/*/*Mapper.xml"

修改测试用例

@Test
    public void save() {
        //插入
        User user = new User();
        user.setAge(18);
        user.setName("小红");
        user.setEmail("wcbc01110@126.com");
        user.setSex(SexEnum.WOMEN);
        userMapper.insert(user);
        //查询
        Long id = user.getId();
        User userInsert = this.userMapper.selectById(id);
        System.out.println(userInsert.toString());
        //更新
        user.setAge(27);
        user.setName("更新后的姓名");
        user.setEmail("qqqq@123.com");
        this.userMapper.updateById(user);
        System.out.println(user.toString());
        //删除
        this.userMapper.deleteById(id);
    }

效果
在这里插入图片描述

mybatis-plus-分页插件

BaseMapper 已经集成的方法

    @Test
    public void page() {
        List<User> userList = userMapper.selectList(null);
        userList.forEach(System.out::println);
        QueryWrapper<User> params = new QueryWrapper<>();
        params.ge("age",22);
        
        Integer count = this.userMapper.selectCount(params);
        System.out.println(count);
        if(count>0){
            Page<User> userPage = new Page<>();
            userPage.setSize(10);
            userPage.setCurrent(1);
            /**
             * 这个方法其实在底层是执行了两个方法  一个count  一个list
             */
            Page<User> userPage1 = this.userMapper.selectPage(userPage, params);
            userPage1.getRecords().forEach(System.out::println);
        }
    }

效果

在这里插入图片描述

QueryWrapper的用法

QueryWrapper这个的用法可以参考mybatis-plus的文档
条件构造器

使用插件自定义的page方法

首先需要先集成mybatis-plus父类的插件配置

MybatisPlusConfig
@Configuration
public class MybatisPlusConfig {
    /**
     * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> configuration.setUseDeprecatedExecutor(false);
    }
}
添加自定义的方法

查询的user 并不需要太多字段
Mapper

@Mapper
public interface UserMapper extends BaseMapper<User> {
    Page<User> pageUser(Page<User> page, Integer sex);
}

UserMapper.xml

    <select id="pageUser"  resultType="com.qiuwei.mybatisplus.user.entity.User">
        SELECT id,name FROM user WHERE sex=#{sex}
    </select>

测试

    @Test
    public void pageUser() {
        Page<User> userPage = new Page<>();
        userPage.setSize(10);
        userPage.setCurrent(1);
        Page<User> resoult = this.userMapper.pageUser(userPage, 1);
        resoult.getRecords().forEach(System.out::println);
    }

效果
在这里插入图片描述

mybatis-plus-sql分析插件

需要引入的pom

       <dependency>
            <groupId>p6spy</groupId>
            <artifactId>p6spy</artifactId>
            <version>3.8.0</version>
        </dependency>

application.yaml

spring:
  datasource:
    # 修改了驱动
    driver-class-name: com.p6spy.engine.spy.P6SpyDriver
    type: com.alibaba.druid.pool.DruidDataSource
    # url 需要引入
    url: jdbc:p6spy:mysql://127.0.0.1:3306/plus?characterEncoding=utf-8&useSSL=true
    username: root
    password: 123456
mybatis-plus:
  type-enums-package: com.qiuwei.mybatisplus.*.enums
 #  注意核心文件和mapper映射文件路劲的扫描问题
  config-location: "classpath:mapper/mybatis-config.xml"
  mapper-locations: "classpath*:mapper/*/*Mapper.xml"

效果

在这里插入图片描述

参考文档

mybatis-plus中文文档 : https://baomidou.com/guide

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值