Mybatis-Plus

来源:https://www.cnblogs.com/b10100912/archive/2022/09/17/16702739.html
-Advertisement-
Play Games

#MyBatis Plus 國產的開源框架,基於 MyBatis 核心功能就是簡化 MyBatis 的開發,提高效率。 ##MyBatis Plus 快速上手 官網快速上手案例 Spring Boot(2.3.0) + MyBatis Plus(國產的開源框架,並沒有接入到 Spring 官方孵化器 ...


MyBatis Plus

國產的開源框架,基於 MyBatis

核心功能就是簡化 MyBatis 的開發,提高效率。

MyBatis Plus 快速上手 官網快速上手案例

Spring Boot(2.3.0) + MyBatis Plus(國產的開源框架,並沒有接入到 Spring 官方孵化器中)

1、創建 Maven 工程

2、pom.xml 引入 MyBatis Plus 的依賴

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.3.1.tmp</version>
</dependency>

3、創建實體類

package com.southwind.mybatisplus.entity;

import lombok.Data;

@Data
public class User {
    private Integer id;
    private String name;
    private Integer age;
}

4、創建 Mapper 介面

package com.southwind.mybatisplus.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.southwind.mybatisplus.entity.User;

public interface UserMapper extends BaseMapper<User> {

}

5、配置資料庫application.yml

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/ssmbooks?useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  mapper-locations: classpath:com/bai/mapper/xml/*.xml
server:
  port: 8181

6、啟動類需要添加 @MapperScan("mapper所在的包"),否則無法載入 Mppaer bean。

package com.southwind.mybatisplus;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.southwind.mybatisplus.mapper")
public class MybatisplusApplication {

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

}

7、測試

package com.southwind.mybatisplus.mapper;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class UserMapperTest {

    @Autowired
    private UserMapper mapper;

    @Test
    void test(){
        mapper.selectList(null).forEach(System.out::println);
    }

}

Mybatis-Plus常用註解

@TableName

映射資料庫的表名

package com.southwind.mybatisplus.entity;

import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

@Data
@TableName(value = "user")
public class Account {
    private Integer id;
    private String name;
    private Integer age;
}

@TableId

設置主鍵映射:

value 映射主鍵欄位名

type 設置主鍵類型,主鍵的生成策略,

AUTO(0),
NONE(1),
INPUT(2),
ASSIGN_ID(3),
ASSIGN_UUID(4),
/** @deprecated */
@Deprecated
ID_WORKER(3),
/** @deprecated */
@Deprecated
ID_WORKER_STR(3),
/** @deprecated */
@Deprecated
UUID(4);
描述
AUTO 資料庫自增
NONE MP set 主鍵,雪花演算法實現
INPUT 需要開發者手動賦值
ASSIGN_ID MP 分配 ID,Long、Integer、String
ASSIGN_UUID 分配 UUID,Strinig

INPUT 如果開發者沒有手動賦值,則資料庫通過自增的方式給主鍵賦值,如果開發者手動賦值,則存入該值。

AUTO 預設就是資料庫自增,開發者無需賦值。

ASSIGN_ID MP 自動賦值,雪花演算法。

ASSIGN_UUID 主鍵的數據類型必須是 String,自動生成 UUID 進行賦值

@TableField

映射非主鍵欄位:

value 映射欄位名

exist 表示是否為資料庫欄位 false,如果實體類中的成員變數在資料庫中沒有對應的欄位,則可以使用 exist,VO、DTO

select 表示是否查詢該欄位

fill 表示是否自動填充,將對象存入資料庫的時候,由 MyBatis Plus 自動給某些欄位賦值,create_time、update_time

實體類中添加成員變數

package com.southwind.mybatisplus.entity;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

import java.util.Date;

@Data
@TableName(value = "user")
public class User {
    @TableId
    private String id;
    @TableField(value = "name",select = false)
    private String title;
    private Integer age;
    @TableField(exist = false)
    private String gender;
    @TableField(fill = FieldFill.INSERT)
    private Date createTime;
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;
}

@TableLogic

映射邏輯刪除
1、數據表添加 deleted 欄位

2、實體類添加註解
@TableLogic private Integer deleted;
3、application.yml 添加配置

global-config:
  db-config:
    logic-not-delete-value: 0
    logic-delete-value: 1

查詢

	mapper.selectList(null);
QueryWrapper wrapper = new QueryWrapper();
        Map<String,Object> map = new HashMap<>();
        map.put("name","小紅");
        map.put("age",3);
        wrapper.allEq(map);
        wrapper.gt("age",2);
        wrapper.ne("name","小紅");
        wrapper.ge("age",2);

//like '%小'
        wrapper.likeLeft("name","小");
//like '小%'
        wrapper.likeRight("name","小");

//inSQL
        wrapper.inSql("id","select id from user where id < 10");
        wrapper.inSql("age","select age from user where age > 3");

        wrapper.orderByDesc("age");

        wrapper.orderByAsc("age");
        wrapper.having("id > 8");

mapper.selectList(wrapper).forEach(System.out::println);
        System.out.println(mapper.selectById(7));
        mapper.selectBatchIds(Arrays.asList(7,8,9)).forEach(System.out::println);

//Map 只能做等值判斷,邏輯判斷需要使用 Wrapper 來處理
        Map<String,Object> map = new HashMap<>();
        map.put("id",7);
        mapper.selectByMap(map).forEach(System.out::println);

QueryWrapper wrapper = new QueryWrapper();
wrapper.eq("id",7);
        System.out.println(mapper.selectCount(wrapper));

        //將查詢的結果集封裝到Map中
        mapper.selectMaps(wrapper).forEach(System.out::println);
        System.out.println("-------------------");
        mapper.selectList(wrapper).forEach(System.out::println);

//分頁查詢
        Page<User> page = new Page<>(2,2);
        Page<User> result = mapper.selectPage(page,null);
        System.out.println(result.getSize());
        System.out.println(result.getTotal());
        result.getRecords().forEach(System.out::println);

        Page<Map<String,Object>> page = new Page<>(1,2);
        mapper.selectMapsPage(page,null).getRecords().forEach(System.out::println);

        mapper.selectObjs(null).forEach(System.out::println);


System.out.println(mapper.selectOne(wrapper));

自定義 SQL(多表關聯查詢)

package com.southwind.mybatisplus.entity;

import lombok.Data;

@Data
public class ProductVO {
    private Integer category;
    private Integer count;
    private String description;
    private Integer userId;
    private String userName;
}
package com.southwind.mybatisplus.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.southwind.mybatisplus.entity.ProductVO;
import com.southwind.mybatisplus.entity.User;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface UserMapper extends BaseMapper<User> {
    @Select("select p.*,u.name userName from product p,user u where p.user_id = u.id and u.id = #{id}")
    List<ProductVO> productList(Integer id);
}

添加

User user = new User();
user.setTitle("小明");
user.setAge(22);
mapper.insert(user);
System.out.println(user);

刪除

//mapper.deleteById(1);
//        mapper.deleteBatchIds(Arrays.asList(7,8));
//        QueryWrapper wrapper = new QueryWrapper();
//        wrapper.eq("age",14);
//        mapper.delete(wrapper);

Map<String,Object> map = new HashMap<>();
map.put("id",10);
mapper.deleteByMap(map);

修改

//        //update ... version = 3 where version = 2
//        User user = mapper.selectById(7);
//        user.setTitle("一號");
//
//        //update ... version = 3 where version = 2
//        User user1 = mapper.selectById(7);
//        user1.setTitle("二號");
//
//        mapper.updateById(user1);
//        mapper.updateById(user);

User user = mapper.selectById(1);
user.setTitle("小紅");
QueryWrapper wrapper = new QueryWrapper();
wrapper.eq("age",22);
mapper.update(user,wrapper);

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

-Advertisement-
Play Games
更多相關文章
  • 推導步驟1:在img標簽的src屬性里放上驗證碼的請求路徑 補充1.img的src屬性: 1.圖片路徑 2.url 3.圖片的二進位數據 補充2:字體樣式 我們電腦上之所以可以輸出各種各樣的字體樣式,其內部其實對應的是一個個以.ttf結尾的文件 由於img的src屬性里可以放圖片的二進位數據,因此 ...
  • 類的定義 面向過程 :是一種以過程為中心的編程思想,實現功能的每一步,都是自己實現的 面向對象 :是一種以對象為中心的編程思想,通過指揮對象實現具體的功能 類的理解 類是對現實生活中一類具有共同屬性和行為的事物的抽象 類是對象的數據類型,類是具有相同屬性和行為的一組對象的集合 簡單理解:類就是對現實 ...
  • 字元串: 註意:字元串是不能修改的,它不像列表一樣,可以修改其中某個元素, 所有對字元串修改操作其實都是相當於生成了一份新數據。就是copy一份改的 字元串常用操作: 註意:字元串是不能修改的,它不像列表一樣,可以修改其中某個元素, 所有對字元串修改操作其實都是相當於生成了一份新數據。就是copy一 ...
  • 1 關於自動記憶體管理 Java是由jvm來管理記憶體,包括自動分配以及自動回收,因此它不容易出現記憶體泄漏和記憶體溢出問題。 C/C++,由程式員手動管理記憶體,手動完成:使用前申請記憶體,使用後釋放記憶體。 2 運行時數據區域 Java虛擬機在執行Java程式的過程中會把它所管理的記憶體劃分為若幹個不同的數據區 ...
  • 前言 嗨嘍~大家好呀,這裡是魔王吶! 今日,一款名為“羊了個羊”微信小游戲火爆全網。由於太火,伺服器2天崩了3次,官方開始急招後端伺服器開發。 “其實游戲很簡單,就是湊齊三個一樣的圖案就能點擊消除,湊不齊三個的圖案先放在底部的七個待選欄位里 如果七個槽位都占滿了,游戲就失敗了。” 這個小游戲火爆的原 ...
  • MyBatis的緩存分為一級緩存和二級緩存。 先看一下MyBatis官方文檔給出的說明: MyBatis 內置了一個強大的事務性查詢緩存機制,它可以非常方便地配置和定製。 為了使它更加強大而且易於配置,我們對 MyBatis 3 中的緩存實現進行了許多改進。 預設情況下,只啟用了本地的會話緩存,它僅 ...
  • 前面我們已經學習了動態SQL的if、where、set、choose(when,otherwise),今天我們來學習剩下的foreach。 什麼時候用到foreach呢?比如說我們要查詢一個表中id為1,3,4的數據,我們應該寫SQL語句為: select * from TABLE where (i ...
  • 一、什麼是SQL片段 就是將我們Mapper.xml文件中部分SQL語句拿出來單獨用一個sql標簽進行標記,這個sql標簽就是一個SQL片段。 二、為什麼要用到SQL片段 這個sql標簽可以被引用,這樣需要用到這個sql標簽中的SQL語句的地方直接引用就可以,如此一來就提高了SQL代碼的復用性,而不 ...
一周排行
    -Advertisement-
    Play Games
  • Dapr Outbox 是1.12中的功能。 本文只介紹Dapr Outbox 執行流程,Dapr Outbox基本用法請閱讀官方文檔 。本文中appID=order-processor,topic=orders 本文前提知識:熟悉Dapr狀態管理、Dapr發佈訂閱和Outbox 模式。 Outbo ...
  • 引言 在前幾章我們深度講解了單元測試和集成測試的基礎知識,這一章我們來講解一下代碼覆蓋率,代碼覆蓋率是單元測試運行的度量值,覆蓋率通常以百分比表示,用於衡量代碼被測試覆蓋的程度,幫助開發人員評估測試用例的質量和代碼的健壯性。常見的覆蓋率包括語句覆蓋率(Line Coverage)、分支覆蓋率(Bra ...
  • 前言 本文介紹瞭如何使用S7.NET庫實現對西門子PLC DB塊數據的讀寫,記錄了使用電腦模擬,模擬PLC,自至完成測試的詳細流程,並重點介紹了在這個過程中的易錯點,供參考。 用到的軟體: 1.Windows環境下鏈路層網路訪問的行業標準工具(WinPcap_4_1_3.exe)下載鏈接:http ...
  • 從依賴倒置原則(Dependency Inversion Principle, DIP)到控制反轉(Inversion of Control, IoC)再到依賴註入(Dependency Injection, DI)的演進過程,我們可以理解為一種逐步抽象和解耦的設計思想。這種思想在C#等面向對象的編 ...
  • 關於Python中的私有屬性和私有方法 Python對於類的成員沒有嚴格的訪問控制限制,這與其他面相對對象語言有區別。關於私有屬性和私有方法,有如下要點: 1、通常我們約定,兩個下劃線開頭的屬性是私有的(private)。其他為公共的(public); 2、類內部可以訪問私有屬性(方法); 3、類外 ...
  • C++ 訪問說明符 訪問說明符是 C++ 中控制類成員(屬性和方法)可訪問性的關鍵字。它們用於封裝類數據並保護其免受意外修改或濫用。 三種訪問說明符: public:允許從類外部的任何地方訪問成員。 private:僅允許在類內部訪問成員。 protected:允許在類內部及其派生類中訪問成員。 示 ...
  • 寫這個隨筆說一下C++的static_cast和dynamic_cast用在子類與父類的指針轉換時的一些事宜。首先,【static_cast,dynamic_cast】【父類指針,子類指針】,兩兩一組,共有4種組合:用 static_cast 父類轉子類、用 static_cast 子類轉父類、使用 ...
  • /******************************************************************************************************** * * * 設計雙向鏈表的介面 * * * * Copyright (c) 2023-2 ...
  • 相信接觸過spring做開發的小伙伴們一定使用過@ComponentScan註解 @ComponentScan("com.wangm.lifecycle") public class AppConfig { } @ComponentScan指定basePackage,將包下的類按照一定規則註冊成Be ...
  • 操作系統 :CentOS 7.6_x64 opensips版本: 2.4.9 python版本:2.7.5 python作為腳本語言,使用起來很方便,查了下opensips的文檔,支持使用python腳本寫邏輯代碼。今天整理下CentOS7環境下opensips2.4.9的python模塊筆記及使用 ...