MyBatisPlus学习笔记

1. 简介

官 网:mybatisplus官网
视频地址:b站狂神说MyBatisPlus最新完整教程通俗易懂

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

2. 特征

  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
  • 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
  • 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
  • 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
  • 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题
  • 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作
  • 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
  • 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用
  • 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
  • 分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库
  • 内置性能分析插件:可输出 Sql 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
  • 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作

3. 快速开始

3.1 依赖

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

3.2 建表,创建springboot项目,连接数据库

3.3 建立数据库字段对应实体类

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

3.4 mapper接口

继承BaseMapper接口,里面有常用的数据库操作方法

@Repository
public interface UserMapper extends BaseMapper<User> {

	//继承了BaseMapper, 所有的方法都来自己父类
    //我们也可以编写自己的扩展方法
}

注意点:需要在主启动类MybatisPlusApplication上扫描我们Mapper包下的所有接口

@MapperScan("com.wang.mapper")

3.5 测试

 @Test
    void contextLoads() {

		//参数是一个Wrapper , 条件构造器,这里我们先不用 --null
        List<User> list = userMapper.selectList(null);
        for (User user : list) {
            System.out.println(user);
        }
    }

4 配置日志

application.yml

# 日志
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

5 CRUD拓展

5.1 插入数据

@Test
    public void testInsert(){
        User user = new User(null,"xiaoman",21,"test6@163.com");
        userMapper.insert(user);
    }

帮我们自动生成id,插入的id默认值为:全局的唯一id
在这里插入图片描述

5.2 主键生成策略

全局唯一ID生成策略
Mybatis-plus 主键生成策略

默认 ID_WORKER 全局唯一id

snowflake是Twitter开源的分布式ID生成算法,结果是一个long型的ID。其核心思想是:使用41bit作为毫秒数,10bit作为机器的ID(5个bit是数据中心(北京,上海…),5个bit的机器ID),12bit作为毫秒内的流水号(意味着每个节点在每毫秒可以产生 4096 个 ID),最后还有一个符号位,永远是0.可以保证几乎全球唯一

修改主键生成策略
例如配置主键自增:

  1. 实体类id字段上加上@TableId(type = IdType.AUTO)
  2. 数据库字段一定要是自增!
    在这里插入图片描述

其余源码解释

public enum IdType {
    AUTO(0),     //自增
    NONE(1),	//未设置主键
    INPUT(2),	//手动输入
    ID_WORKER(3),   //默认全局唯一id
    UUID(4),		//全局唯一id uuid
    ID_WORKER_STR(5);   //ID_WORKER字符串表示

    private int key;

    private IdType(int key) {
        this.key = key;
    }

    public int getKey() {
        return this.key;
    }
}

5.3 更新操作

注意:updateById()参数是 一个对象!

 	@Test
    public void testUpdate(){
        User user = new User(1358306497330683906L,"xiaoliu",20,"test7@163.com");
        userMapper.updateById(user);
    }

5.4 自动填充

创建时间 . 修改时间! 这些个操作都是自动化完成的,我们不希望手动更新!

阿里巴巴开发手册:所有的数据库表:gmt_create .gmt_modified几乎所有的表都要配置上!而且需要自动化!

方式一: 数据库级别(工作中不建议使用)
  1. 在表中新增字段 create_time , update_time
    在这里插入图片描述
  2. 再次测试插入方法,我们需要先把实体类同步

注意:要导入util包下面的Data,不然会用lombok

 private Data creatTime;
 private Data updateTime;
  1. 测试
方式二: 代码级别
  1. 删除数据库默认值
    在这里插入图片描述

  2. 实体类字段属性上添加注解

    @TableField(fill = FieldFill.INSERT)
    private Data creatTime;
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Data updateTime;
  1. 编写处理器来处理这个注解
@Slf4j      //日志
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    //插入时的填充策略
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill...");

        this.setFieldValByName("createTime",new Date(),metaObject);
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }
    //更新时的填充策略
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update  fill...");
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }
}

  1. 测试

5.5 乐观锁和悲观锁

乐观锁: 顾名思义十分乐观,他总是认为不会出现问题,无论干什么都不去上锁!如果出现了问题,再次更新值测试
悲观锁;顾名思义十分悲观,他总是认为出现问题,无论干什么都会上锁!再去操作!

当要更新一条记录的时候,希望这条记录没有被别人更新
乐观锁实现方式:

  • 取出记录时,获取当前version
  • 更新时,带上这个version
  • 执行更新时, set version = newVersion where version = oldVersion
  • 如果version不对,就更新失败

在这里插入图片描述

5.1.1 测试一下mybatis乐观锁插件
5.1.1.1 给数据表中加入version字段

在这里插入图片描述

5.1.1.2 同步实体类
 @Version   //乐观锁version注解
 private Integer version;
5.1.1.3 注册组件
/**
 * @program: mybatis_plus
 * @description: mybatisplus配置类
 * @author: Mr.Wang
 * @create: 2021-02-07 19:51
 **/

@Configuration  //配置类
@EnableTransactionManagement  //自动管理事务
public class MybatisPlusConfig {

    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor(){
        return new OptimisticLockerInterceptor();
    }
}

5.1.1.4 测试乐观锁成功
	@Test
    public void testOptimisticLockerInterceptor01(){

        //查询用户信息
        User user = userMapper.selectById(1L);

        //更改用户信息
        user.setName("zjr");
        user.setAge(20);
        user.setEmail("123456@163.com");

        //执行修改
        userMapper.updateById(user);

    }
5.1.1.5 测试乐观锁失败
 //测试乐观锁失败
    @Test
    public void testOptimisticLockerInterceptor02(){
        //线程1
        User user = userMapper.selectById(1L);
        user.setName("lp");

        //模拟线程插队
        User user1 = userMapper.selectById(1L);
        user1.setName("tsy");
        userMapper.updateById(user1);

        //如果没有乐观锁就会覆盖插队线程的值
        userMapper.updateById(user);
    }

5.6 查询操作

	//测试查询
    @Test
    public void testSelectById(){
        User user = userMapper.selectById(1L);
        System.out.println(user);
    }

    //测试批量查询
    @Test
    public void testSelectBatchId(){
        List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
        users.forEach(System.out::println);
    }

    //按条件查询 之一使用map操作
    @Test
    public void testSelectByMap(){
        HashMap<String, Object> map = new HashMap<>();
        map.put("name","tsy");
        map.put("age","20");
        List<User> users = userMapper.selectByMap(map);
        users.forEach(System.out::println);
    }

5.7 分页查询

5.7.1 配置拦截器组件
	//分页插件
	@Bean
    public PaginationInterceptor paginationInterceptor(){
        return new PaginationInterceptor();
    }
5.7.2 测试分页查询
 //测试分页查询
    @Test
    public void testPage(){
        //参数1当前页,参数2页面大小
        Page<User> page = new Page<>(1,5);
        userMapper.selectPage(page,null);

        page.getRecords().forEach(System.out::println);
    }

5.7.3 集成PageHelper分页
5.7.3.1 依赖
 <dependency>
 	<groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.3.0</version>
 </dependency>
5.7.3.2 使用
	public PageInfo<Department> deptListPage(QueryPageVO vo) {
        PageHelper.startPage(vo.getPageNumber(), vo.getPageSize());
        List<Department> departmentList = deptMapper.selectList(null);
        PageInfo<Department> page = new PageInfo<>(departmentList);
        return page;
    }

5.8 逻辑删除

普通删除
在这里插入图片描述

物理删除:从数据库中直接移除
逻辑删除: 在数据库中没有被移除,而是通过一个变量来让他失效! deleted=0=>deleted=1

管理员可以查看被删除的记录!防止数据的丢失,类似于回收站!

5.8.1 在数据表中增加deleted字段

在这里插入图片描述

5.8.2 实体类中增加属性
	@TableLogic
    private Integer deleted;
5.8.3 配置
 	//注册逻辑删除组件
    @Bean
    public ISqlInjector sqlInjector(){
        return new LogicSqlInjector();
    }
# 配置逻辑删除    
mybatis-plus:
  global-config:
    db-config:
      logic-not-delete-value: 0
      logic-delete-value: 1

5.9 性能分析插件

我们在平时的开发中,会遇到一些慢sql.

mybatis也提供了性能分析插件,如果超过这个时间就停止运行!

5.9.1 导入插件
	@Bean
    @Profile({"dev","test"}) //设置dev 和 test环境开启
    public PerformanceInterceptor performanceInterceptor(){
        PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
        performanceInterceptor.setMaxTime(100);		//设置sql最大执行时间,超过就不执行
        performanceInterceptor.setFormat(true);
        return performanceInterceptor;
    }

设置开发环境

 profiles:
    active: dev
5.9.2 测试使用

5.10 条件构造器Wrapper

我们写一些复杂sql就可以用它代替
在这里插入图片描述

@SpringBootTest
public class WrapperTest {

    @Autowired
    private UserMapper userMapper;
    @Test
    void contextLoads() {
        // 查询name不为空的用户,并且邮箱不为空的用户,年龄大于等于20
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.
                isNotNull("name")
                .isNotNull("email")
                .ge("age",20);
        List<User> users = userMapper.selectList(wrapper);
        users.forEach(System.out::println);
    }

    @Test
    void test01(){
        //查询名字等于xiaoman
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("name","xiaoman");
        User user = userMapper.selectOne(wrapper);
        System.out.println(user);
    }

    @Test
    void test02(){
        //查询年龄在21 - 25之间的用户数量
        QueryWrapper<User> wrapper= new QueryWrapper<>();
        wrapper.between("age",21,25);
        Integer count = userMapper.selectCount(wrapper);
        System.out.println(count);
    }

    @Test
    void test03(){
        //模糊查询:名字中不包含'l'并且包含'a'的
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper
                .notLike("name","l")
                .like("name","a");
        List<User> users = userMapper.selectList(wrapper);
        users.forEach(System.out::println);

    }

    @Test
    void test04(){
        //id在子查询中查出来
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.inSql("id","select id from user where id < 3");
        List<User> users = userMapper.selectList(wrapper);
        users.forEach(System.out::println);
    }

    @Test
    void test05(){
        //通过age排序
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("age");
        List<User> users = userMapper.selectList(wrapper);
        users.forEach(System.out::println);
    }
}

5.11 代码自动生成器

AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。
依赖

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

        <!--MyBatis-Plus 从 3.0.3 之后移除了代码生成器与模板引擎的默认依赖,需要手动添加相关依赖:-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.3.1.tmp</version>
        </dependency>

        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
            <version>1.7</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>

代码

package com.wang;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.util.ArrayList;

/**
 * @program: mybatis_plus
 * @description: 代码自动生成器
 * @author: Mr.Wang
 * @create: 2021-02-08 11:34
 **/
public class WangCode {
    public static void main(String[] args) {
        //需要构建一个 代码自动生成器 对象
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();
        //配置策略

        //1、全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("xiaoman");
        gc.setOpen(false);      //是否打开windows文件夹
        gc.setFileOverride(false);  //是否覆盖
        gc.setServiceName("%sService");  //去Service的I前缀
        gc.setIdType(IdType.ID_WORKER);
        gc.setDateType(DateType.ONLY_DATE);
        gc.setSwagger2(true);
        mpg.setGlobalConfig(gc);

        //2、设置数据源
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/db_mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("18170021");
        dsc.setDbType(DbType.MYSQL);
        mpg.setDataSource(dsc);

        //3、包的配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName("blog");
        pc.setParent("com.wang");
        pc.setEntity("entity");
        pc.setMapper("mapper");
        pc.setService("service");
        pc.setController("controller");
        mpg.setPackageInfo(pc);

        //4、策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setInclude("user");    //设置要映射的表名,可包含多张表
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);    //自动lombok
        strategy.setLogicDeleteFieldName("deleted");   //逻辑删除
        //自动填充配置
        TableFill createTime = new TableFill("create_time", FieldFill.INSERT);
        TableFill updateTime = new TableFill("update_time", FieldFill.UPDATE);
        ArrayList<TableFill> tableFills = new ArrayList<>();
        tableFills.add(createTime);
        tableFills.add(updateTime);
        strategy.setTableFillList(tableFills);
        //乐观锁
        strategy.setVersionFieldName("version");
        strategy.setRestControllerStyle(true);
        strategy.setControllerMappingHyphenStyle(true);     //localhost:8080/hello_id_2
        mpg.setStrategy(strategy);

        mpg.execute();  //执行代码构造器
    }
}

完结撒花
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值