• MybatisPlus


    学习视频链接:狂神说Java

    一、简介

    1、 启动会自动注入基本的CRUD,性能基本无损耗,直接面向对象操作。
    2、内通用的Mapper、Service,仅通过少量的配置就可以实现单表大部分的CRUD操作,有条件构造器来满足各类的使用需求
    3、内置代码生成器,采用代码或者maven插件快速生成mapper、model、service、controller层代码。
    4、内置分页插件
    5、内置全局拦截插件

    使用第三方组件:
    1、导入对应的依赖
    2、配置
    3、代码的编写

    二、基本操作的使用

    1、创建新的工程
    2、导入对应的坐标依赖

            <!--数据库驱动,基本的连接驱动-->
            
                mysql
                mysql-connector-java
            
            
            
                org.projectlombok
                lombok
            
    
            <!--mybatis-plus-->
            
            
                com.baomidou
                mybatis-plus-boot-starter
                3.0.5
            
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    3、配置application.yml
    mysql8 驱动不同 com.mysql.jdbc.Driver 需要增加时区的配置 serverTime=GMT%2B8

    spring:
      datasource:
        username: root
        password: 123456
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/mybatis_pplus?useUnicode=true&characterEncoding=utf8
        
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    4、创建实体类

    package com.tiki.entity;
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class User {
        private Long id;
        private String name;
        private Integer age;
        private String email;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    5、创建mapper接口

    package com.tiki.mapper;
    import com.baomidou.mybatisplus.core.mapper.BaseMapper;
    import com.tiki.entity.User;
    //在对应的Mapper上面继承基本的类 BaseMapper
    @Repository//表示是dao层
    public interface UserMapper extends BaseMapper<User> {
        //所有的CRUD操作都已经编写完成,不需要在像之前一样配置很多文件
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    6、在启动类上配置需要扫描的类

    package com.tiki;
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    @MapperScan("com.tiki.mapper")//扫描mapper包下的所有接口
    @SpringBootApplication
    public class MybatisPlusApplication {
        public static void main(String[] args) {
            SpringApplication.run(MybatisPlusApplication.class, args);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    7、测试

    package com.tiki;
    import com.tiki.entity.User;
    import com.tiki.mapper.UserMapper;
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import java.util.List;
    @SpringBootTest
    class MybatisPlusApplicationTests {
    
        //继承了BaseMapper,所有的方法都来自父类,也可自己编写扩展方法
        @Autowired
        private UserMapper userMapper;
        @Test
        void contextLoads() {
            //查询全部用户,参数是一个wrapper,条件构造器,当查询全部的时候,值为空
            List<User> users = userMapper.selectList(null);
            users.forEach(System.out::println);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    配置日志

    由于所有的sql语句现在是不可见的,锁客可以通过日志的方法查看它是怎么执行的

    在控制台输出

    mybatis-plus:
      configuration:
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    
    • 1
    • 2
    • 3

    CRUD

    1、插入操作

    @Test
        public void testInsert(){
            User user = new User();
            user.setName("小明");
            user.setAge(3);
            user.setEmail("123456@123.com");
            int result=userMapper.insert(user);//会自动生成id
            System.out.println(result);//受影响的行数
            System.out.println(user);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    在这里插入图片描述

    主键自增:
    1、在实体类的字段上增加注解 @TableId(type=IdType.AUTO)
    2、数据库的字段对应也需要设置成自增

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

    2、更新操作

    //测试更新
        @Test
        public void testUpdate(){
            User user = new User();
            user.setId(1568498212239384580L);
            user.setName("更新小明");
            user.setAge(3);
            user.setEmail("123456@123.com");
            //updateById()的对象是对应的实体类
            int i = userMapper.updateById(user);
            System.out.println(i);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    自动填充
    创建时间、修改时间,这些操作都需要自动化完成。
    方式一:数据库级别
    1、在表中新增字段 create_time、update_time
    在这里插入图片描述2、同步更新实体类

     private Date createTime;
     private Date updateTime;
    
    • 1
    • 2

    3、再次更新操作

     public void testUpdate(){
            User user = new User();
            user.setId(1568498212239384580L);
            user.setName("更新小明");
            user.setAge(19);
            user.setEmail("123456@123.com");
            //updateById()的 对象是对应的实体类
            int i = userMapper.updateById(user);
            System.out.println(i);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    方式二:代码级别
    1、删除数据库的默认值
    2、实体类字段属性上需要增加注解

        //字段添加填充内容
        @TableField(fill = FieldFill.INSERT)
        private Date createTime;
        @TableField(fill = FieldFill.INSERT_UPDATE)
        private Date updateTime;
    
    • 1
    • 2
    • 3
    • 4
    • 5

    3、编写处理器来处理该注解

    package com.tiki.handler;
    import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.ibatis.reflection.MetaObject;
    import org.springframework.stereotype.Component;
    import java.util.Date;
    @Slf4j //日志
    @Component //交给springboot管理,将处理器加到IOC容器中
    public class MyMetaObjectHandler implements MetaObjectHandler {
        //插入时候的填充策略
        @Override
        public void insertFill(MetaObject metaObject) {
            log.info("start insert fill...");
            //setFieldValByName(String fieldName, Object fieldVal, MetaObject metaObject)
            this.setFieldValByName("createTime",new Date(),metaObject);
            this.setFieldValByName("updateTime",new Date(),metaObject);
        }
        //更新时候的填充策略
        @Override
        public void updateFill(MetaObject metaObject) {
            log.info("start uodate fill...");
            this.setFieldValByName("updateTime",new Date(),metaObject);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    在这里插入图片描述

    在这里插入图片描述
    乐观锁
    乐观锁:总是认为不会出现问题,无论干什么都不加锁,如果出现了问题,再次更新值测试。
    悲观锁:总是认为出现问题,无论干什么都会上锁!再去操作!

    乐观锁的实现方式:
    1、取出记录时,获取当前的version
    2、更新时,带上这个version
    3、执行更新时,set version=newVersion shere version=oldVersion
    4、如果version不对,就更新失败。
    –A
    update user set name=“Aila”,version=version+1 where id=2 and version=1
    –B线程B在A之前完成该操作,会使得此时的version已经变成2,A就会修改失败。
    update user set name=“Aila”,version=version+1 where id=2 and version=1

    实现步骤:
    1、给数据库字段增加version字段
    在这里插入图片描述2、实体类添加对应的字段

     @Version//乐观锁version的注解
     private Integer version;
    
    • 1
    • 2

    3、注册组件

    package com.tiki.config;
    
    import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.transaction.annotation.EnableTransactionManagement;
    
    @EnableTransactionManagement //开启事务管理,此时就可以将写在启动类下的扫描注解移动到该类中
    @MapperScan("com.tiki.mapper")//扫描mapper接口下的所有类
    @Configuration //配置类
    public class MyBatisPlusConfig {
        //注册乐观锁插件
        @Bean
        public OptimisticLockerInterceptor optimisticLockerInterceptor(){
            return new OptimisticLockerInterceptor();
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    4、测试

      //测试乐观锁
        @Test
        public void testOptimisticLocker(){
            //1.查询用户信息
            User user = userMapper.selectById(1L);
            //2、修改用户信息
            user.setName("Baddy");
            user.setEmail("12456321@qq.com");
            userMapper.updateById(user);
        }
    
        //测试乐观锁失败!多线程下
        @Test
        public void testOptimisticLocker2(){
    
            //线程1
            User user = userMapper.selectById(1L);
            user.setName("Baddy");
            user.setEmail("12456321@qq.com");
    
            //模拟另一个线程执行插队操作
            User user2 = userMapper.selectById(1L);
            user2.setName("Baddyyyyyyyyy");
            user2.setEmail("12456321@qq.com");
            userMapper.updateById(user2);
    
            userMapper.updateById(user);//如果没有乐观锁就会覆盖插队线程的值
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    在这里插入图片描述
    查询:
    按照分页查询

    //条件查询使用map
        @Test
        public void testSelectByBatchIds(){
            HashMap<String, Object> map = new HashMap<>();
            //自定义查询的条件
            map.put("name","TiKiL");
    
            List<User> users=userMapper.selectByMap(map);
            users.forEach(System.out::println);
    
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    分页查询:
    1、配置拦截器组件

        //分页插件
        @Bean
        public PaginationInterceptor paginationInterceptor(){
            return new PaginationInterceptor();
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2、直接使用Page对象即可

        //测试分页查询
        @Test
        public void  testPage(){
            Page<User> page = new Page<>(1,5);//参数一:当前页 参数二:页面大小
            userMapper.selectPage(page,null);
            page.getRecords().forEach(System.out::println);
            System.out.println(page.getTotal());
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    删除操作
    1、基本的删除操作

        //测试删除
        @Test
        public void testDeleteById(){
            userMapper.deleteById(1568498212239384580L);
        }
    
        //通过id批量删除
        @Test
        public void testDeleteBatchId(){
            userMapper.deleteBatchIds(Arrays.asList(1568498212239384580L,1568498212239384579L));
        }
    
        //通过map删除
        @Test
        public void testDeleteMap(){
            HashMap<String, Object> map = new HashMap<>();
            map.put("name","小明");
            userMapper.deleteByMap(map);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    2、逻辑删除

    物理删除:从数据库中直接移除
    逻辑删除:数据库当中并没有实际删除数据,只是通过一个变量让该数据失效。(如:管理员可以查看被删除的数据!防止数据的丢失,类似于回收站)
    1、在数据表中增加一个deleted字段
    在这里插入图片描述
    2、实体类中增加属性

       @TableLogic//逻辑删除
        private Integer deleted;
    
    • 1
    • 2

    3、配置(在config类中添加逻辑删除组件)

        //逻辑删除组件
        @Bean
        public ISqlInjector  sqlInjector(){
            return new LogicSqlInjector();
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    application.yml中添加配置,配置逻辑删除【】

    mybatis-plus:
      configuration:
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
      global-config:
        db-config:
          logic-delete-value: 1
          logic-not-delete-value: 0
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
        @Test
        public void testDeleteById(){
            userMapper.deleteById(3L);
        }
    
    • 1
    • 2
    • 3
    • 4

    本质做的是更新操作,并不是删除操作
    在这里插入图片描述在这里插入图片描述在这里插入图片描述

    性能分析插件

    作用:性能分析拦截器,用于输出每条SQL语句及其执行时间
    1、导入插件(在配置类中)

        //sql执行效率插件
        @Bean
        @Profile({"dev","test"}) //设置dev test环境开启==>开发测试环境开启
        public PerformanceInterceptor performanceInterceptor(){
            PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
            performanceInterceptor.setMaxTime(100);//ms 设置sql执行的最大时间,如果超过则不执行
            performanceInterceptor.setFormat(true);
            return performanceInterceptor;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    在springboot的配置中(application.yml)开启dev/test环境的配置

    spring:
      profiles:
        active: dev
    
    • 1
    • 2
    • 3

    2、测试使用

    条件构造器–Wrapper

    1、查询name不为空的用户,并且邮箱不为空的用户,年龄大于等于12

     @Test
        void contextLoads(){ 
            QueryWrapper<User>wrapper=new QueryWrapper<>();
            wrapper.isNotNull("name")
                    .isNotNull("email")
                    .ge("age",12);
            userMapper.selectList(wrapper).forEach(System.out::println);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    2、 查询名字为TiKi

        @Test
        void test2(){
          
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("name","TiKi");
            User user = userMapper.selectOne(wrapper);//查询一个数据,出现多个使用List或者map
            System.out.println(user);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    3、查询年龄在20~30岁之间的用户

    @Test
        void test3(){
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.between("age",20,30);//区间
            Integer count=userMapper.selectCount(wrapper);//查询结果数
            System.out.println(count);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    4、模糊查询

    @Test
        void test4(){
            //likeRight和likeLeft指的是%在左或者右
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper
                    .notLike("name","e")//%e%
                    .likeRight("email","t");//t%
            List<Map<String, Object>> maps = userMapper.selectMaps(wrapper);
            maps.forEach(System.out::println);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    5、

    @Test
        void test5(){
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            //id在子查询中查出来
            wrapper.inSql("id","select id from user where id<3");
            List<Object> objects = userMapper.selectObjs(wrapper);
            objects.forEach(System.out::println);
    
        }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    在这里插入图片描述6、排序

        @Test
        void test6(){
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            //通过id进行排序
            wrapper.orderByDesc("id");
            List<User> users = userMapper.selectList(wrapper);
            users.forEach(System.out::println);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    代码生成器

    package com.tiki;
    
    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;
    
    /**
     * @description: ${description}
     * @Title: TiKicode
     * @Package com.tiki
     * @Author TiTi
     * @Date 2022/9/12 15:45
     */
    public class TiKicode {
        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("TiKi");
            gc.setOpen(false);
            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/mybatis_pplus?useUnicode=true&characterEncoding=utf8");
            dsc.setDriverName("com.mysql.cj.jdbc.Driver");
            dsc.setUsername("root");
            dsc.setPassword("123456");
            dsc.setDbType(DbType.MYSQL);
            mpg.setDataSource(dsc);
    
            //3、包的配置
            PackageConfig packageConfig = new PackageConfig();
            packageConfig.setModuleName("blog");
            packageConfig.setParent("com.TiKioo");
            packageConfig.setEntity("entity");
            packageConfig.setMapper("mapper");
            packageConfig.setService("service");
            packageConfig.setController("controller");
            mpg.setPackageInfo(packageConfig);
    
            //4、策略配置
            StrategyConfig strategy = new StrategyConfig();
            //重要!!!设置需要映射的表名
            strategy.setInclude("user");//如果有多个表 strategy.setInclude("user",“course”,"records");
            //设置包的命名规则
            strategy.setNaming(NamingStrategy.underline_to_camel);
            //设置列的命名规则
            strategy.setColumnNaming(NamingStrategy.underline_to_camel);
            //strategy.setSuperEntityClass("自己的父类实体,没有就不用设置");
            strategy.setEntityLombokModel(true);//自动lombok
            strategy.setRestControllerStyle(true);
            strategy.setControllerMappingHyphenStyle(true);
            strategy.setLogicDeleteFieldName("deleted");//逻辑删除字段的名称
            //自动填充配置
            TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);
            TableFill gmtMofified = new TableFill("gmt_mofified", FieldFill.INSERT_UPDATE);
            ArrayList<TableFill> tableFills = new ArrayList<>();
            tableFills.add(gmtCreate);
            tableFills.add(gmtMofified);
            strategy.setTableFillList(tableFills);
            //乐观锁
            strategy.setVersionFieldName("version");
            mpg.setStrategy(strategy);
            mpg.execute();
    
    
    
    
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92

    在这里插入图片描述

  • 相关阅读:
    数据分析---Python与sql
    90后小伙以这196道MySQL面试题,实力吊打面试官,生生挤进大厂
    聊聊设计模式——中介者模式
    【LeetCode-中等题】904. 水果成篮
    flink重温笔记(十六): flinkSQL 顶层 API ——实时数据流结合外部系统
    并发:线程状态
    重邮803计网概述
    C++ Qt开发:Slider滑块条组件
    老年少女测试媛入职感想
    C++获取变量的类型和名称
  • 原文地址:https://blog.csdn.net/Apikaqiu/article/details/126788403