天天看點

springboot整合mybatis和mybatis-plus

springboot整合mybatis

  • 導入相關的jar包
    • <!--引入資料庫驅動 -->
             <dependency>
                 <groupId>mysql</groupId>
                 <artifactId>mysql-connector-java</artifactId>
                 <scope>runtime</scope>
             </dependency>
        
             <!--springBoot資料庫連接配接  -->
             <dependency>
                 <groupId>org.springframework.boot</groupId>
                 <artifactId>spring-boot-starter-jdbc</artifactId>
             </dependency>
        
             <!--spring整合mybatis  暫時  -->
             <dependency>
                 <groupId>org.mybatis.spring.boot</groupId>
                 <artifactId>mybatis-spring-boot-starter</artifactId>
                 <version>2.2.0</version>
             </dependency>
                 
  • 編輯配置檔案
    • #端口配置
      server:
        port: 8090
      
      #配置資料源
      spring:
        datasource:
          #如果使用高版本驅動 則添加cj
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://127.0.0.1:3306/jt?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
          username: root
          password: 1998
      
      #Spring整合Mybatis
      mybatis:
        #定義别名包
        type-aliases-package: com.jt.pojo
        #導入映射檔案
        mapper-locations: classpath:/mappers/*.xml
        #開啟駝峰映射
        configuration:
          map-underscore-to-camel-case: true
      
      
                 
    • 資料庫配置的參數:
      • serverTimezone=GMT%2B8& 時區
      • useUnicode=true& 是否使用unicode編碼
      • characterEncoding=utf8& 字元集使用utf-8
      • autoReconnect=true& 自動重連
      • allowMultiQueries=true 運作批量操作
  • 編輯映射檔案
    • <?xml version="1.0" encoding="UTF-8" ?>
      <!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
      <mapper namespace="com.jt.mapper.UserMapper">
      
          <!--Oracle中 ;号必定報錯  不要加;号  -->
          <select id="findAll" resultType="com.jt.pojo.User">
              select * from demo_user
          </select>
      
      </mapper>
                 
  • 編輯對應接口
    • springboot整合mybatis和mybatis-plus

mybatis-plus學習

ORM思想

  • 對象關系映射(英語:Object Relational Mapping,簡稱ORM,或O/RM,或O/R mapping),是一種程式設計技術,用于實作面向對象程式設計語言裡不同類型系統的資料之間的轉換。

    總結: 以面向對象的方式操作資料庫.

    知識升華:

    • 以對象的方式實作資料庫的CRUD操作
    • 要求通過某種機制将對象動态的轉換為sql,之後實作資料庫操作(自己不寫sql)

mybatis的優缺點

優點

  • mybatis内部整合了jdbc,簡化了持久層的開發
  • mybatis可以自動的封裝結果集,滿足ORM中的一個跳進啊,是以将mybatis稱之為半自動化的ORM映射架構
  • mybatis有緩存機制 一級緩存/二級緩存 提高使用者的查詢效率
  • mybatis支援多種類型的資料庫,整合簡單

缺點

  • 實作資料的封裝 resultMap 封裝複雜
  • 針對與單表的CRUD的操作,不夠便捷,sql需要手寫
  • 個别情況下二級緩存配置不生效

mybatis-plus介紹

  • MyBatis-Plus (opens new window)(簡稱 MP)是一個 MyBatis (opens new window)的增強工具,在 MyBatis 的基礎上隻做增強不做改變,為簡化開發、提高效率而生。

    特性:

    無侵入:隻做增強不做改變,引入它不會對現有工程産生影響,如絲般順滑

    損耗小:啟動即會自動注入基本 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 操作智能分析阻斷,也可自定義攔截規則,預防誤操作

mp的入門案例

導入jar包
<!--spring整合mybatis-plus 删除mybatis的包 -->
  <dependency>
       <groupId>com.baomidou</groupId>
       <artifactId>mybatis-plus-boot-starter</artifactId>
       <version>3.4.3</version>
   </dependency>
           
實作映射
  • 關鍵詞:對象 表 屬性 字段 一一映射
  • 說明:
    • 對象名稱與表的名稱一一對應
    • 對象的屬性與表中的屬性一一對應
  • springboot整合mybatis和mybatis-plus
繼承特定的接口
  • 關鍵詞:封裝-多态-繼承
  • 說明:mp在内部準備一個BaseMapper的接口 BaseMapper内部幾乎将單表的CRUD操作 都進行了編輯 使用者自己的Mapper接口繼承即可
  • springboot整合mybatis和mybatis-plus
編輯配置檔案
#Spring整合MP
mybatis-plus:
  #定義别名包
  type-aliases-package: com.jt.pojo
  #導入映射檔案
  mapper-locations: classpath:/mappers/*.xml
  #開啟駝峰映射
  configuration:
    map-underscore-to-camel-case: true
           

配置檔案内容和mybatis是一樣的,隻是最上面的mybatis改成了mybatis-plus

MP的操作原理

核心理論

1.例子: userMapper.insert(user);

dogMapper.insert(dog);

Sql:

  1. insert into 表名(字段名稱…) value (屬性的值…)

總結: MP将正常的操作進行抽取, 采用公共的接口進行定義. 之後隻需要按照使用者的參數, 動态的拼接Sql即可.

MP理論流程

重點:對Java反射機制有一定的了解

  1. userMapper.insert(user) 使用者調用接口方法,完成業務
  2. 根據使用者傳遞的對象:user.getClass(),擷取的是類型.

    Class userClass = user.getClass();

  3. 根據class類型,通過反射動态擷取指定的注解

    TableName tableName = (TableName) userClass.getAnnotation(TableName.class);

  4. 擷取表名 String 表名 = tableName.value();
  5. 根據User的類型可以擷取屬性名稱. 根據屬性名稱 可以擷取注解 @TableField(“name”),

    最終擷取字段的名稱.

  6. 拼接Sql: insert into demo_user(id,age,name,sex) value (user.getId()…)
  7. 最終将Sql 由MP交給Mybatis執行sql. 最終實作資料的入庫操作.

MP中常用的方法學習

selectById(Integer id)

//1.查詢ID查詢資料庫 id=231  主鍵查詢
    @Test
    public void selectById(){
        int id = 231;   //模拟使用者參數.
        User user = userMapper.selectById(id);
        System.out.println(user);
    }
           

selectList(QueryWrapper queryWrapper)

/**
     * 2.查詢 name="小喬" 并且 性别 ="女"
     * 思路: 如果将來有多個結果 則使用List進行接收.
     * Sql: select * from demo_user where name="小喬" and sex="女"
     * 注意事項: 預設的連接配接符  and
     */
    @Test
    public void select01(){
        //1.通過對象封裝資料
        User user = new User();
        user.setName("小喬").setSex("女");
        //2.建構條件構造器 根據對象中不為null的屬性充當where條件!
        QueryWrapper<User> queryWrapper = new QueryWrapper(user);
        //3.根據條件構造器 實作資料查詢
        List<User> userList = userMapper.selectList(queryWrapper);
        System.out.println(userList);
    }


 /**
     * 3.查詢 name="小喬" 并且 性别 ="女"
     * 邏輯運算符:  = eq, > gt, < lt
     *            >= ge, <= le
     *            != ne
     */
    @Test
    public void select02(){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name","小喬")
                    .eq("sex","女");
        List<User> userList =
                userMapper.selectList(queryWrapper);
        System.out.println(userList);
    }


  /**
     * 5.select  查詢  name包含 '君'字的資料
     * 關鍵字:  like "%xxx%"
     *         以君開頭:  likeRight "君%"
     *         以君結尾:  likeLeft  "%君"
     */
    @Test
    public void select04(){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.like("name","君");
        List<User> userList = userMapper.selectList(queryWrapper);
        System.out.println(userList);
    }


 /**
     *  7.需求: 動态Sql查詢. 如果資料有值 則拼接where條件.
     *                   如果資料為null 則不拼接where條件
     *  文法: condition: true  拼接where條件
     *                  false 不拼接where條件
     */
    @Test
    public void select06(){
        String name = "貂蟬";
        int age = 19;
        boolean nameFlag = name == null ? false : true;
        boolean ageFlag = age == 0 ? false : true;
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.eq(nameFlag,"name",name)
                    .eq(ageFlag,"age",age);
        List<User> userList = userMapper.selectList(queryWrapper);
        System.out.println(userList);
    }
           

selectBatchIds(集合)

/**
     * 8.批量查詢  查詢id= 1,4,5,6......的資料
     */
    @Test
    public void selectIn(){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id",1,4,5,6);
        List<User> userList = userMapper.selectList(queryWrapper);
        System.out.println(userList);

        //數組在未來由使用者負責傳遞. 注意使用包裝類型
        Integer[] array = new Integer[]{1,4,5,6};
        //數組轉化為List集合
        List ids = Arrays.asList(array);
        List<User> userList2 = userMapper.selectBatchIds(ids);
        System.out.println(userList2);
    }
           

selectObjs(QueryWrapper queryWrapper)

/**
     * 9.查詢性别為男的使用者,隻查詢ID字段
     *  selectObjs(); 隻查詢第一列字段(主鍵)
     *  實際用途:  根據業務隻需要主鍵的查詢
     */
    @Test
    public void selectObjs(){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sex","男");
        List<Object> ids = userMapper.selectObjs(queryWrapper);
        System.out.println(ids);
    }
           

updateById(Object obj)

/**
     * 1.将ID=231的資料 name改為 "xx"
     * Sql: update demo_user set name="xx" where id=231

     */
    @Test
    public void testUpdate(){
        User user = new User();
        user.setId(231).setName("中秋節快樂").setAge(10).setSex("男");
        //byId 表示ID隻當作where條件.
        //其它不為null的屬性 當作set條件
        userMapper.updateById(user);
    }
           

update()

/**
     *
     * @param user
     * @param name
     *
     * update(arg1,arg2)
     *      arg1:set條件的資料
     *      arg2:where條件的資料
     */
    @Override
    public void updateUserByName(User user, String name) {
//        upadtewrapper和querywrapper功能一樣可以混用
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name);
        userMapper.update(user,queryWrapper);
    }
           

關于查詢的總結

  • MP核心:以對象的方式操作資料庫
  • 條件構造器:new QueryWrapper<>(); 動态拼接where條件
  • 拼接規則:根據對象中不為null的屬性充當where條件
  • 特殊轉義字元:= eq;> gt ; < lt; <= le ; >= ge ; != ne
  • xml檔案中的萬能轉義字元:<![CDATA[sql語句]]>
  • 關鍵字: like , order by , in
  • 動态sql文法:
    • condition:true拼接where條件

      ​ false不拼接where條件