mybatis-plus入門

来源:https://www.cnblogs.com/wandaren/archive/2022/11/21/16906568.html
-Advertisement-
Play Games

1、快速開始 1.1、現有一張 User 表,其表結構如下 | id | name | age | emali | | | | | | | 1 | Jone | 18 | [email protected] | | 2 | Jack | 20 | [email protected] | | 3 ...


1、快速開始

1.1、現有一張 User 表,其表結構如下

id name age emali
1 Jone 18 [email protected]
2 Jack 20 [email protected]
3 Tom 28 [email protected]
4 Sandy 21 [email protected]
5 Billie 24 [email protected]
  • SQL語句
DROP TABLE IF EXISTS user;

CREATE TABLE `user` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT '主鍵ID',
  `name` varchar(30) DEFAULT NULL COMMENT '姓名',
  `age` int DEFAULT NULL COMMENT '年齡',
  `email` varchar(50) DEFAULT NULL COMMENT '郵箱',
  `is_deleted` int NOT NULL DEFAULT '0' COMMENT '邏輯刪除',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

DELETE FROM user;

INSERT INTO user (id, name, age, email,is_deleted) VALUES
(1, 'Jone', 18, '[email protected]',0),
(2, 'Jack', 20, '[email protected]',0),
(3, 'Tom', 28, '[email protected]',0),
(4, 'Sandy', 21, '[email protected]',0),
(5, 'Billie', 24, '[email protected]',0);

1.2、引入依賴

  • mybatis-plus-boot-starter
       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.11</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

1.3、配置資料庫連接,開啟控制台SQL語句輸出

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://114.67.111.175:3306/test
    username: wq
    password: 123456
#開啟控制台日誌
mybatis-plus:
  configuration:
    #控制台列印sql語句方便調試sql語句執行錯誤
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    #這個不在控制台列印查詢結果,但是在log4j2中列印
    #log-impl: org.apache.ibatis.logging.log4j2.Log4j2Impl
  • 在 Spring Boot 啟動類中添加 @MapperScan 註解,掃描 Mapper 文件夾:
@SpringBootApplication
@MapperScan("com.wanqi.mybatisplus.mapper")
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

1.4、編碼

  • 實體類User
package com.wanqi.mybatisplus.pojo;


import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;

@TableName("user") //指定表名
public class User {
    //type = IdType.AUTO自增欄位需要修改資料庫主鍵為自增
    //value指定對應主鍵欄位名,type指定id生成策略(預設策略為雪花演算法)
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;
    //value資料庫欄位值
    @TableField(value = "name")
    private String name;
    private Integer age;
    private String email;
    private Integer isDeleted;


    public User(Long id, String name, Integer age, String email) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.email = email;
    }
    public User(String name, Integer age, String email) {
        this.name = name;
        this.age = age;
        this.email = email;
    }

    public User() {
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

   public Integer getIsDeleted() {
        return isDeleted;
    }

    public void setIsDeleted(Integer isDeleted) {
        this.isDeleted = isDeleted;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", email='" + email + '\'' +
                ", isDeleted=" + isDeleted +
                '}';
    }
}

  • 編寫 Mapper 包下的 UserMapper介面
import com.wanqi.mybatisplus.pojo.User;
import org.springframework.stereotype.Repository;

@Repository
public interface UserMapper extends BaseMapper<User> {

}

1.5、測試使用

package com.wanqi.mybatisplus;

import com.wanqi.mybatisplus.mapper.UserMapper;
import com.wanqi.mybatisplus.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@SpringBootTest
class MybatisPlusApplicationTests {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void testSelect() {
        System.out.println(("----- selectAll method test ------"));
        userMapper.insert(new User( "古力娜扎", 18, "[email protected]"));

        List<User> userList = userMapper.selectList(null);
        userList.forEach(System.out::println);
    }
}

2、批量操作

2.1、增加Service 層代碼

package com.wanqi.mybatisplus.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.wanqi.mybatisplus.pojo.User;

/**
 * @Description TODO
 * @Version 1.0.0
 * @Date 2022/9/1
 * @Author wandaren
 */
public interface UserService extends IService<User> {
}

  • 註意 UserServiceImpl 必須要繼承 MP 框架中的 ServiceImpl,不然要重寫很多方法。
package com.wanqi.mybatisplus.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wanqi.mybatisplus.mapper.UserMapper;
import com.wanqi.mybatisplus.pojo.User;
import org.springframework.stereotype.Service;

/**
 * @Description TODO
 * @Version 1.0.0
 * @Date 2022/9/1
 * @Author wandaren
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> 
    implements UserService{
}

2.2、測試使用

package com.wanqi.mybatisplus;

import com.wanqi.mybatisplus.mapper.UserMapper;
import com.wanqi.mybatisplus.pojo.User;
import com.wanqi.mybatisplus.service.UserServiceImpl;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@SpringBootTest

class MybatisPlusApplicationTests {
    @Autowired
    private UserServiceImpl userService;

    @Test
    void contextLoads() {
        Collection<User> userList = new ArrayList<>();
        userList.add(new User("hhh", 18, "[email protected]"));
        userList.add(new User("sss", 18, "[email protected]"));
        userList.add(new User("ddd", 18, "[email protected]"));
        userService.saveBatch(userList);
        System.out.println(userService.list());
    }
}

3、Service CURD

3.1、save

// 插入一條記錄(選擇欄位,策略插入)
boolean save(T entity);
// 插入(批量)
boolean saveBatch(Collection<T> entityList);
// 插入(批量)
boolean saveBatch(Collection<T> entityList, int batchSize);

image.png

3.2、saveOrUpdate

// TableId 註解存在更新記錄,否插入一條記錄
boolean saveOrUpdate(T entity);
// 根據updateWrapper嘗試更新,否繼續執行saveOrUpdate(T)方法
boolean saveOrUpdate(T entity, Wrapper<T> updateWrapper);
// 批量修改插入
boolean saveOrUpdateBatch(Collection<T> entityList);
// 批量修改插入
boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize);

image.png

3.3、remove

// 根據 entity 條件,刪除記錄
boolean remove(Wrapper<T> queryWrapper);
// 根據 ID 刪除
boolean removeById(Serializable id);
// 根據 columnMap 條件,刪除記錄
boolean removeByMap(Map<String, Object> columnMap);
// 刪除(根據ID 批量刪除)
boolean removeByIds(Collection<? extends Serializable> idList);

image.png

3.4、update

// 根據 UpdateWrapper 條件,更新記錄 需要設置sqlset
boolean update(Wrapper<T> updateWrapper);
// 根據 whereWrapper 條件,更新記錄
boolean update(T updateEntity, Wrapper<T> whereWrapper);
// 根據 ID 選擇修改
boolean updateById(T entity);
// 根據ID 批量更新
boolean updateBatchById(Collection<T> entityList);
// 根據ID 批量更新
boolean updateBatchById(Collection<T> entityList, int batchSize);

image.png

3.5、get

// 根據 ID 查詢
T getById(Serializable id);
// 根據 Wrapper,查詢一條記錄。結果集,如果是多個會拋出異常,隨機取一條加上限制條件 wrapper.last("LIMIT 1")
T getOne(Wrapper<T> queryWrapper);
// 根據 Wrapper,查詢一條記錄
T getOne(Wrapper<T> queryWrapper, boolean throwEx);
// 根據 Wrapper,查詢一條記錄
Map<String, Object> getMap(Wrapper<T> queryWrapper);
// 根據 Wrapper,查詢一條記錄
<V> V getObj(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);

image.png

3.6、List

// 查詢所有
List<T> list();
// 查詢列表
List<T> list(Wrapper<T> queryWrapper);
// 查詢(根據ID 批量查詢)
Collection<T> listByIds(Collection<? extends Serializable> idList);
// 查詢(根據 columnMap 條件)
Collection<T> listByMap(Map<String, Object> columnMap);
// 查詢所有列表
List<Map<String, Object>> listMaps();
// 查詢列表
List<Map<String, Object>> listMaps(Wrapper<T> queryWrapper);
// 查詢全部記錄
List<Object> listObjs();
// 查詢全部記錄
<V> List<V> listObjs(Function<? super Object, V> mapper);
// 根據 Wrapper 條件,查詢全部記錄
List<Object> listObjs(Wrapper<T> queryWrapper);
// 根據 Wrapper 條件,查詢全部記錄
<V> List<V> listObjs(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);

image.png

3.7、page

// 無條件分頁查詢
IPage<T> page(IPage<T> page);
// 條件分頁查詢
IPage<T> page(IPage<T> page, Wrapper<T> queryWrapper);
// 無條件分頁查詢
IPage<Map<String, Object>> pageMaps(IPage<T> page);
// 條件分頁查詢
IPage<Map<String, Object>> pageMaps(IPage<T> page, Wrapper<T> queryWrapper);

image.png

4、邏輯刪除

  • 方式一:使用註解TableLogic
// value邏輯未刪除值,delval邏輯刪除值
@TableLogic(value = "0", delval = "1")
private Integer isDeleted;
  • 方式二:使用全局配置
mybatis-plus:
  global-config:
    db-config:
      logic-delete-field: isDeleted # 全局邏輯刪除的實體欄位名
      logic-delete-value: 1 # 邏輯已刪除值(預設為 1)
      logic-not-delete-value: 0 # 邏輯未刪除值(預設為 0)

5、分頁

  • 配置
package com.wanqi.mybatisplus.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Description TODO
 * @Version 1.0.0
 * @Date 2022/9/24
 * @Author wandaren
 */
@Configuration
public class CustomMyBatisPlusConfig {
    /**
     * 分頁插件,一緩和二緩遵循mybatis的規則
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(DbType.MYSQL);
        // 設置請求的頁面大於最大頁後操作, true調回到首頁,false 繼續請求  預設false
        // paginationInnerInterceptor.setOverflow(false);
        // 設置最大單頁限制數量,預設 500 條,-1 不受限制
        // paginationInnerInterceptor.setMaxLimit(500L);
        interceptor.addInnerInterceptor(paginationInnerInterceptor);
        return interceptor;
    }

}
  • 測試
    @Test
    void page() {
        long l = System.currentTimeMillis();
        Page<VoteRecord> page = new Page<>(99999, 20);
        final Page<VoteRecord> voteRecordPage = voteRecordMapper.selectPage(page, null);
        voteRecordPage.getRecords().forEach(System.out::println);
        System.out.println(System.currentTimeMillis() -l);
    }

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • Java異常 1.概念理解 異常(Exepotion)指程式運行過程中不期而至的各種狀況,它阻止了程式按照程式員的預期正常執行,這就是異常(開發過程中的語法錯誤和1.邏輯錯誤不是異常)。如文件找不到,網路連接失敗,非法參數等。 異常發生在程式運行期間,影響程式的正常執行。 2.常見異常分類 **檢查 ...
  • WEB開發會話技術02 6.Cookie的生命周期 預設情況下,Cookie只在瀏覽器的記憶體中存活,也就是說,當你關閉瀏覽器後,Cookie就會消失。但是也可以通過方法設置cookie的生存時間。 cookie的生命周期指的是如何管理cookie,什麼時候cookie被銷毀。 setMaxAge(i ...
  • 全局有序 在RocketMQ中,如果使消息全局有序,可以為Topic設置一個消息隊列,使用一個生產者單線程發送數據,消費者端也使用單線程進行消費,從而保證消息的全局有序,但是這種方式效率低,一般不使用。 局部有序 假設一個Topic分配了兩個消息隊列,生產者在發送消息的時候,可以對消息設置一個路由I ...
  • 目錄 一.簡介 二.freeglut + glew 三.glfw + glad 四.猜你喜歡 零基礎 OpenGL ES 學習路線推薦 : OpenGL ES 學習目錄 >> OpenGL ES 基礎 零基礎 OpenGL ES 學習路線推薦 : OpenGL ES 學習目錄 >> OpenGL E ...
  • 一.小結 1.標識符是程式中事務的名稱 2.標誌符是由字母 數字 下劃線 和美元符號$構成的字元序列 3.標識符必須以字母或下劃線開頭,不能以數字開頭 4.標識符不能是保留字 5.標識符可以是任意長度 6.選擇描述性的標識符可提高程式的可讀性 7.使用變數存儲在程式中使用的數據 8.聲明變數就是告訴 ...
  • 大家好,歡迎來到 Crossin的編程教室 ! 前幾天,後臺老有小伙伴留言“愛心代碼”。這不是Crossin很早之前發過的內容嘛,怎麼最近突然又被人翻出來了?後來才知道,原來是一部有關程式員的青春偶像劇《點燃我,溫暖你》在熱播,而劇中有一段關於期中考試要用程式畫一個愛心的橋段。 於是出於好奇,Cro ...
  • 列表和字典的區別是列表可以通過索引來訪問值,而字典可以通過名稱來訪問各個值。 字典這種數據結構稱為映射(mapping),字典是Python中唯一內置映射類型,值不按照順序排列,而是存儲再鍵下麵。 其中鍵可以是數字、字元串或元組等不可變數據類型。 字典的用途 字典的名稱指出了這種數據結構的用途。日常 ...
  • 來源:blog.csdn.net/u014454538/article/details/98515807 1. Java中的線程安全 Java線程安全:狹義地認為是多線程之間共用數據的訪問。 Java語言中各種操作共用的數據有5種類型:不可變、絕對線程安全、相對線程安全、線程相容、線程獨立 ① 不可 ...
一周排行
    -Advertisement-
    Play Games
  • 1、預覽地址:http://139.155.137.144:9012 2、qq群:801913255 一、前言 隨著網路的發展,企業對於信息系統數據的保密工作愈發重視,不同身份、角色對於數據的訪問許可權都應該大相徑庭。 列如 1、不同登錄人員對一個數據列表的可見度是不一樣的,如數據列、數據行、數據按鈕 ...
  • 前言 上一篇文章寫瞭如何使用RabbitMQ做個簡單的發送郵件項目,然後評論也是比較多,也是準備去學習一下如何確保RabbitMQ的消息可靠性,但是由於時間原因,先來說說設計模式中的簡單工廠模式吧! 在瞭解簡單工廠模式之前,我們要知道C#是一款面向對象的高級程式語言。它有3大特性,封裝、繼承、多態。 ...
  • Nodify學習 一:介紹與使用 - 可樂_加冰 - 博客園 (cnblogs.com) Nodify學習 二:添加節點 - 可樂_加冰 - 博客園 (cnblogs.com) 介紹 Nodify是一個WPF基於節點的編輯器控制項,其中包含一系列節點、連接和連接器組件,旨在簡化構建基於節點的工具的過程 ...
  • 創建一個webapi項目做測試使用。 創建新控制器,搭建一個基礎框架,包括獲取當天日期、wiki的請求地址等 創建一個Http請求幫助類以及方法,用於獲取指定URL的信息 使用http請求訪問指定url,先運行一下,看看返回的內容。內容如圖右邊所示,實際上是一個Json數據。我們主要解析 大事記 部 ...
  • 最近在不少自媒體上看到有關.NET與C#的資訊與評價,感覺大家對.NET與C#還是不太瞭解,尤其是對2016年6月發佈的跨平臺.NET Core 1.0,更是知之甚少。在考慮一番之後,還是決定寫點東西總結一下,也回顧一下.NET的發展歷史。 首先,你沒看錯,.NET是跨平臺的,可以在Windows、 ...
  • Nodify學習 一:介紹與使用 - 可樂_加冰 - 博客園 (cnblogs.com) Nodify學習 二:添加節點 - 可樂_加冰 - 博客園 (cnblogs.com) 添加節點(nodes) 通過上一篇我們已經創建好了編輯器實例現在我們為編輯器添加一個節點 添加model和viewmode ...
  • 前言 資料庫併發,數據審計和軟刪除一直是數據持久化方面的經典問題。早些時候,這些工作需要手寫複雜的SQL或者通過存儲過程和觸發器實現。手寫複雜SQL對軟體可維護性構成了相當大的挑戰,隨著SQL字數的變多,用到的嵌套和複雜語法增加,可讀性和可維護性的難度是幾何級暴漲。因此如何在實現功能的同時控制這些S ...
  • 類型檢查和轉換:當你需要檢查對象是否為特定類型,並且希望在同一時間內將其轉換為那個類型時,模式匹配提供了一種更簡潔的方式來完成這一任務,避免了使用傳統的as和is操作符後還需要進行額外的null檢查。 複雜條件邏輯:在處理複雜的條件邏輯時,特別是涉及到多個條件和類型的情況下,使用模式匹配可以使代碼更 ...
  • 在日常開發中,我們經常需要和文件打交道,特別是桌面開發,有時候就會需要載入大批量的文件,而且可能還會存在部分文件缺失的情況,那麼如何才能快速的判斷文件是否存在呢?如果處理不當的,且文件數量比較多的時候,可能會造成卡頓等情況,進而影響程式的使用體驗。今天就以一個簡單的小例子,簡述兩種不同的判斷文件是否... ...
  • 前言 資料庫併發,數據審計和軟刪除一直是數據持久化方面的經典問題。早些時候,這些工作需要手寫複雜的SQL或者通過存儲過程和觸發器實現。手寫複雜SQL對軟體可維護性構成了相當大的挑戰,隨著SQL字數的變多,用到的嵌套和複雜語法增加,可讀性和可維護性的難度是幾何級暴漲。因此如何在實現功能的同時控制這些S ...