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(); //執行
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM