MyBatis-Plus 常用註解

相關標籤:1.MyBatis 更流暢的使用體驗
2.強大實用:MyBatis 與三種流式查詢方法

MyBatis-Plus 常用註解

那些年,我們一起學過的 MyBatis-Plus 常用註解

一、MyBatis-Plus 常用註解簡介

最近學習了 MyBatis-Plus,現在帶大家回顧一下在學習過程中經常用到哪些註解,這些註解有什麼功能?如何使用這些註解?特別適合新手學習和老手複習~

話不多說,讓我們開始吧!

2. MyBatis-Plus 簡介
MyBatis-Plus(簡稱 MP)是 MyBatis 的增強工具。在 MyBatis 的基礎上只做增強不做改變,為簡化開發、提高效率而生。

願景是做 MyBatis 最好的搭檔!

官方地址:https://baomidou.com/

文檔發布地址:https://baomidou.com/pages/24112f



3.MyBatis-Plus 常用註解·常用註解
1. @MapperScan
@SpringBootApplication _
@MapperScan ( " com.cabbage.mapper " )
public class Mybatisplus01Application {
public static void main( String[] args ) {
SpringApplication.run ( Mybatisplus01Application.class, args );
}
}

結合代碼和圖片,大家可以猜到:@MapperScan 註解用於掃描 mapper 對應檔,只有使用了它才能使用官方提供的各種方法。

2. @Mapper
@Mapper
@Repository
public interface UserMapper extends BaseMapper {
/**
* Query to map collection according to id
* @param id
* @return
*/
Map< String,Object > selectMapById (Long id);
}

為什麼再次介紹這個註解呢?因為 @Mapper 作用於資料庫中的實體類,不需要再寫 @MapperScan 註解。它們的區別在於:@Mapper 只能映射一個實體類,而 @MapperScan 可以映射整個包下的實體類,範圍更廣,操作更方便。

3. @TableName
先看以下代碼:

@Data
//Set the table name corresponding to the entity class
@TableName("t_user")
public class User {
@TableId(value = "id",type = IdType.AUTO)
private Long uid;
@TableField(value = "name")
private String name;
private Integer age;
private String email;
@TableField(value = "is_deleted")
@TableLogic
private Integer isDeleted ;
}



大家都知道,當實體類的類名與要操作的表名不一致時會報錯,@TableName 註解可以協助我們解決這個問題。資料庫表名是 t_user,實體類名是 User,只需在類名上寫 @TableName("t_user") 即可。

4. @Data
這個註解也大幅簡化了開發。為什麼這麼說呢?因為使用這個註解後,可以省略 getter()、setter()、toString(),以及類的 equals() 和 hashCode() 方法的重寫。是不是很驚喜?

5. @TableId
MyBatis-Plus 執行增刪改查時,預設使用 id 作為主鍵列,插入資料時預設
基於雪花演算法產生 id,這裡不展開講解雪花演算法。

使用 @TableId(value = "id") 時,如果實體類和表中的主鍵不是 id 而是其他欄位(如代碼中的 uid),MyBatis-Plus 會自動識別 uid 為主鍵列,否則會報錯:

使用 @TableId(value = "id", type = IdType.AUTO) 表示使用資料庫自增策略。注意,使用此 type 時請確保資料庫已設定 id 自增,否則會失效!

當然,@TableId 的功能也可以寫在 application.yml 設定檔中,配置如下:

mybatis -plus:
global-config:
banner: false
db -config:
# Configure the default prefix of the MyBatis -Plus operation table
table-prefix: "t_"
# Configure the primary key strategy of MyBatis -Plus
id-type: auto
# Configure MyBatis logs
configuration:
log - impl : org.apache.ibatis.logging.stdout.StdOutImpl

6. @TableField
MyBatis-Plus 執行 SQL 陳述式時,必須保證實體類中的屬性名稱與表中的欄位名相同,否則會報錯。@TableField(value = "is_deleted") 表示將資料庫表中的 is_deleted 與實體類中的 isDeleted 欄位名對應。

注意:

如果實體類屬性使用駝峰命名風格,表中欄位使用底線命名風格
例如實體類屬性 userName,表欄位 user_name,MyBatis-Plus 會自動將底線命名風格轉換為駝峰命名風格
如果實體類屬性與表中欄位不符合上述條件,如實體類屬性 name 與表欄位 username,需要在實體類屬性上使用 @TableField("username") 設定該屬性對應的欄位名

7. @TableLogic

在講這個註解之前,先來瞭解一下邏輯刪除。

物理刪除:真實刪除,從資料庫中刪除對應資料,刪除後無法查詢到該資料
邏輯刪除:假刪除,將對應資料中表示是否刪除的欄位狀態改為"已刪除狀態",資料庫中仍可查看該資料記錄
使用情境:可資料恢複

在我的資料庫表中,is_delete 為1時表示邏輯刪除,is_delete 為0時表示未刪除
@TableLogic 註解表示類中的屬性為邏輯刪除屬性

注意:

測試邏輯刪除時,實際執行的是 UPDATE t_user SET is_deleted =1 WHERE id=? AND is_deleted =0
測試查詢功能時,已邏輯刪除的資料預設不會被查詢 SELECT id,username AS name,age,email,is_deleted FROM t_user WHERE is_deleted =0
學習 MyBatis-Plus 分頁外掛程式時,需要配置攔截器,參見代碼:

@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor ( ) {
MybatisPlusInterceptor interceptor =
new MybatisPlusInterceptor ( );

interceptor.addInnerInterceptor
(new PaginationInnerInterceptor ( DbType.MYSQL ));
return interceptor;
}
}

8. @Configuration
相信大家已經多次看到這個註解了,可能有點不耐煩,但我還是要在這裡提一下。使用此註解的類代表配置類,該類本身也是一個 Bean。還可以在此類中使用 @Bean 註解載入 Bean

9. @Bean
@Bean 註解表示將方法中的對象注入到 Spring 容器中,方便後續從容器中取出對象以簡化開發。通常與 @Configuration 註解配合使用。相信大家經常看到這個註解,這裡就不多說了~

講完了分頁外掛程式,來看看基本用法。


@Test
void test01() {
//Set paging parameters
Page page = new Page< >( 1, 3);
userMapper.selectPage (page, null);
//Get pagination data
List list = page.getRecords ();
list.forEach ( System.out :: println );
System.out.println ("Current page:" + page.getCurrent ());
System.out.println ("Number of items displayed per page: " + page.getSize ());
System.out.println ("Total records:" + page.getTotal ());
System.out.println ("Total pages: " + page.getPages ());
System.out.println ("Is there a previous page:" + page.hasPrevious ());
System.out.println ("Whether there is a next page: " + page.hasNext ());
}

運行結果:


10. @Param
使用自訂分頁語句時:

@Mapper
@Repository
public interface UserMapper extends BaseMapper {
/**
* Query user information by age and paginate
* @param page
* @param age
* @return
*/
Page selectPageByAge ( Page page, @Param("age") Integer age);
}





@Param 由 MyBatis 提供。作為 Dao 層註解,用於傳遞參數,使其與 SQL 中的欄位名對應,簡化開發~

11. @Version
學習樂觀鎖時,一定見過以下代碼:

@Data
@TableName("t_product")
public class Product {
private Long id;
private String name;
private Integer price;
@Version
private Integer version;
}

@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor =
new MybatisPlusInterceptor ( );
//Pagination plugin
interceptor.addInnerInterceptor
(new PaginationInnerInterceptor ( DbType.MYSQL ));
//Optimistic lock plugin
interceptor.addInnerInterceptor (new OptimisticLockerInnerInterceptor ());
return interceptor;
}
}

@Version 是實現樂觀鎖的重要註解。當資料庫中的資料需要更新時(如 price),version 會遞增1。如果 where 語句中的 version 不正確,更新將失敗。

MyBatis 常用註解·@EnumValue
@Getter
public enum SexEnum {
MALE(1, "男"),
FEMALE(2, "女");
@EnumValue
private Integer sex;
private String sexName;
SexEnum(Integer sex, String sexName) {
this.sex = sex;
this.sexName = sexName;
}
}

mybatis -plus:
global-config:
banner: false
db -config:
# Configure the default prefix of the MyBatis -Plus operation table
table-prefix: "t_"
# Configure the primary key strategy of MyBatis -Plus
id-type: auto
# Configure MyBatis logs
configuration:
log - impl : org.apache.ibatis.logging.stdout.StdOutImpl
# Configure the package corresponding to the type alias
type-aliases-package: cabbage.pojo
# Configure scan general enumeration
type- enums - package: cabbage.pojo

@EnumValue 註解標識的屬性值將儲存到資料庫中,相當於 INSERT INTO t_user (username, age, sex) VALUES (?, ?, ?)
參數:Enum(String)、20(Integer)、1(Integer)

4.MyBatis 常用註解·總結


好了,MyBatis-Plus 的常用註解差不多講完了。相信大家已經感受到了國產架構的便捷支援,希望大家積極支援。如果覺得博主寫得不錯,可以給博主三連支援~~

相關文章

探索更多特惠

  1. 簡訊服務(SMS)與郵件服務

    5萬封郵件包低至1.99 USD,120條簡訊僅需1.00 USD

phone 聯絡我們
Hi, I'm Alibaba Cloud AI Assistant!
I can help with questions and solutions.