• mybatis-plus常用操作


    官网详细说明

    https://mybatis.plus

    1.自动填充

    对于字段 create_time,update_time ,完成自动更新

     

     执行update操作之后,就不用很呆的去set updateTime了。

    2.乐观锁

    乐观锁

     十分乐观认为不会产生并发问题,每次去取数据的时候总认为不会有其他线程对数据进行修改,因此不会上锁,但是在更新时会判断其他线程在这之前有没有对数据进行修改,一般会使用版本号机制或CAS操作实现。

    乐观锁实现方式:

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

    例:线程1:  获取version = 1时

    update user set name='kerwin',version = version+1 where id = 111 and version =1;

          线程2: 同时获取version = 1时,抢先执行完成,version = 2, 此时线程1执行失败。

    update user set name='wj',version = version+1 where id = 111 and version =1;
    表字段:

     注册组件

    // 扫描mapper 文件夹
    @MapperScan("com.kerwin.mapper")
    @EnableTransactionManagement
    @Configuration // 配置类
    public class MyBatisPlusConfig {
        // 注册乐观锁插件
        @Bean
        public OptimisticLockerInterceptor optimisticLockerInterceptor() {
            return new OptimisticLockerInterceptor();
        }
    }

    线程执行update操作时,如果线程一更新失败,会进入自旋状态,多次尝试。

    3.条件构造器Wrapper

    解决一些复杂查询

    例:

    生成的sql可以通过日志查看

        @Test
        public void test1(){
            //查询name,邮箱不为空,年龄大于20的用户
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.isNotNull("name")
                    .isNotNull("email")
                    .ge("age",20);
           userMapper.selectList(wrapper).forEach(System.out::println);
        }
    
        @Test
        public void test2(){
            //查询name=Tom
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("name","Tom");
            User user = userMapper.selectOne(wrapper);
            System.out.println(user);
        }
    
        @Test
        public void test3(){
            //查询年龄在20-23之间的用户数
            QueryWrapper<User> wrapper = new QueryWrapper<>();
          wrapper.between("age",20,23);
            Integer count = userMapper.selectCount(wrapper);
            System.out.println(count);
        }
    
        @Test
        public void test4(){
            //模糊查询邮箱 test%
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.likeRight("email","test");
            List<User> list = userMapper.selectList(wrapper);
            userMapper.selectList(wrapper).forEach(System.out::println);
    
        }

    4.代码自动生成器

    1.导入mybatis-plus-generator依赖

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

    2.构建代码自动生成对象-->配置环境-->执行。

    package com.kerwin;
    
    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;
    
    public class CodeGenerator {
        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("kerwin");
            gc.setOpen(false);
            gc.setFileOverride(false); // 是否覆盖
            gc.setServiceName("%sService"); // 去Service的I前缀
            gc.setIdType(IdType.AUTO);
            gc.setDateType(DateType.ONLY_DATE);
            gc.setSwagger2(true);
            mpg.setGlobalConfig(gc);
            //2、设置数据源
            DataSourceConfig dsc = new DataSourceConfig();
            dsc.setUrl("jdbc:mysql://localhost:3306/mybatis_plus? useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC");
                    dsc.setDriverName("com.mysql.cj.jdbc.Driver");
            dsc.setUsername("root");
            dsc.setPassword("123");
            dsc.setDbType(DbType.MYSQL);
            mpg.setDataSource(dsc);
            //3、包的配置
            PackageConfig pc = new PackageConfig();
            pc.setModuleName("blog");
            pc.setParent("com.kerwin");
            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 gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);
            TableFill gmtModified = new TableFill("gmt_modified",
            FieldFill.INSERT_UPDATE);
            ArrayList<TableFill> tableFills = new ArrayList<>();
            tableFills.add(gmtCreate);
            tableFills.add(gmtModified);
            strategy.setTableFillList(tableFills);
            // 乐观锁
            strategy.setVersionFieldName("version");
            strategy.setRestControllerStyle(true);
            strategy.setControllerMappingHyphenStyle(true);
            mpg.setStrategy(strategy);
            mpg.execute(); //执行
        }
    }
  • 相关阅读:
    PHP读取MySQL中文乱码
    dotnet如何使用资源文件
    常见的隐藏地址的流媒体下载方法(转)
    圣诞礼物:Google Maps API开发样例一则
    Google EarthMapsKML核心开发技术揭秘 一个完整的Google Maps应用
    WEB界面测试用例~ 收藏
    通过xmlhttp实现报告归档
    转换长日期为短日期
    做delphi控件的笔记
    Reflector使用手记
  • 原文地址:https://www.cnblogs.com/jiezai/p/13551600.html
Copyright © 2020-2023  润新知