Mybatis-Plus學習筆記
特性:
- 無侵入:只做增強不做改變,引入它不會對現有工程產生影響,如絲般順滑
- 損耗小:啟動即會自動注入基本 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 操作智能分析阻斷,也可自定義攔截規則,預防誤操作
環境搭建所需要的依賴:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
然后在spring boot組態檔中配置好資料源以及mybatis-plus配置:
如:
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
注意:匯入mybatis-Plus后不要在匯入任何的mybatis以來了
應用:
創建與資料庫表中相對性的JavaBean物體物件,如果表中欄位帶有下劃線例如user_name,物件屬性以駝峰形式來接,mybatis-plus,會自動進行匹配,
撰寫對應的mapper介面,要繼承BaseMapper<T>,這個類中已經實作了我們常用的CRUD操作,只呼叫即可,而且也不用再寫相對應的物件Mapper.xml了,Sql陳述句我們也不用管理了,下面是BaseMapper<T>中一些方法的使用:
1.測驗查詢:
@Test
public void selectTest(){
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
//查詢案例:查詢批量用戶
@Test
public void testSelectBatchIds(){
List<User> users = userMapper.selectBatchIds(Arrays.asList(21, 22, 23));
users.forEach(System.out::println);
}
//查詢案例:按條件查詢
@Test
public void testSelectBatchId(){
HashMap<String, Object> map = new HashMap<>();
map.put("name", "熊大");
map.put("age", 16);
List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}
//分頁查詢
@Test
public void testPaginationInterceptor(){
Page<User> page = new Page<>(1,2);
userMapper.selectPage(page, null);
System.out.println(page.getTotal());
page.getRecords().forEach(System.out::println);
}
//查詢案例:查詢批量用戶
@Test
public void testSelectBatchIds(){
List<User> users = userMapper.selectBatchIds(Arrays.asList(21, 22, 23));
users.forEach(System.out::println);
}
注意再分頁查詢的時候,需要配置一個分頁查詢組件,一般會專門撰寫一個配置類來管理mybatis=plus所需要的組件:
@Bean//分頁組件
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// 設定請求的頁面大于最大頁后操作, true調回到首頁,false 繼續請求 默認false
// paginationInterceptor.setOverflow(false);
// 設定最大單頁限制數量,默認 500 條,-1 不受限制
// paginationInterceptor.setLimit(500);
// 開啟 count 的 join 優化,只針對部分 left join
paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
return paginationInterceptor;
}
2.測驗插入;
@Test
public void insertTest(){
User user = new User();
user.setAge(16);
user.setName("小明");
user.setEmail("13029228@qq.com");
int insert = userMapper.insert(user);
System.out.println(insert);
}
3 .測驗更新:需要添加樂觀鎖插件
意圖:
當要更新一條記錄的時候,希望這條記錄沒有被別人更新
樂觀鎖實作方式:
- 取出記錄時,獲取當前version
- 更新時,帶上這個version
- 執行更新時, set version = newVersion where version = oldVersion
- 如果version不對,就更新失敗
樂觀鎖配置需要2步 記得兩步
插件配置
1spring boot:
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
2.注解物體欄位 @Version 必須要!
@Version
private Integer version;
特別說明:
- 支持的資料型別只有:int,Integer,long,Long,Date,Timestamp,LocalDateTime
- 整數型別下
newVersion = oldVersion + 1 newVersion會回寫到entity中- 僅支持
updateById(id)與update(entity, wrapper)方法 - 在
update(entity, wrapper)方法下,wrapper不能復用!!!
int id = 100;
int version = 2;
User u = new User();
u.setId(id);
u.setVersion(version);
u.setXXX(xxx);
if(userService.updateById(u)){
System.out.println("Update successfully");
}else{
System.out.println("Update failed due to modified by others");
}
示例SQL原理
update tbl_user set name = 'update',version = 3 where id = 100 and version = 2
4.洗掉(邏輯洗掉)
說明:
只對自動注入的sql起效:
- 插入: 不作限制
- 查找: 追加where條件過濾掉已洗掉資料,且使用 wrapper.entity 生成的where條件會忽略該欄位
- 更新: 追加where條件防止更新到已洗掉資料,且使用 wrapper.entity 生成的where條件會忽略該欄位
- 洗掉: 轉變為 更新
例如:
- 洗掉:
update user set deleted=1 where id = 1 and deleted=0 - 查找:
select id,name,deleted from user where deleted=0
欄位型別支持說明:
- 支持所有資料型別(推薦使用
Integer,Boolean,LocalDateTime) - 如果資料庫欄位使用
datetime,邏輯未洗掉值和已洗掉值支持配置為字串null,另一個值支持配置為函式來獲取值如now()
附錄:
- 邏輯洗掉是為了方便資料恢復和保護資料本身價值等等的一種方案,但實際就是洗掉,
- 如果你需要頻繁查出來看就不應使用邏輯洗掉,而是以一個狀態去表示,
用法:
步驟1: 配置com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig
- 例: application.yml
mybatis-plus:
global-config:
db-config:
logic-delete-field: flag # 全域邏輯洗掉的物體欄位名(since 3.3.0,配置后可以忽略不配置步驟2)
logic-delete-value: 1 # 邏輯已洗掉值(默認為 1)
logic-not-delete-value: 0 # 邏輯未洗掉值(默認為 0)
步驟2: 物體類欄位上加上@TableLogic注解
@TableLogic
private Integer deleted;
另外;
QueryWrapper<User> wrapper = new QueryWrapper<>();能夠對查詢條件做一些篩選
用法:
//條件查詢
@Test
void contextLoads() {
//查詢name不為空并且郵箱也不為空,而且年齡大于等于10
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.isNotNull("name")
.isNotNull("email");
wrapper.between("age", 12, 22);
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}
//模糊查詢
@Test
void test(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
//LikeRight 表示%在右邊
wrapper.notLike("name", "熊") //%熊%
.likeRight("age", 1);//1%
List<Map<String, Object>> maps = userMapper.selectMaps(wrapper);
maps.forEach(System.out::println);
}
/**
* ==> Preparing: SELECT id,name,age,email,create_time,update_time,version,deleted FROM user WHERE deleted=0 AND (name NOT LIKE ? AND age LIKE ?)
* ==> Parameters: %熊%(String), 1%(String)
* <== Columns: id, name, age, email, create_time, update_time, version, deleted
* <== Row: 23, 翠花, 16, 17029228@qq.com, 2020-10-05 11:03:03, 2020-10-05 14:27:40, 1, 0
* <== Row: 24, 小明, 16, 13029228@qq.com, 2020-10-05 11:04:16, 2020-10-05 11:04:16, 1, 0
* <== Row: 29, 小李, 15, , 2020-10-05 15:33:14, 2020-10-05 15:33:19, 1, 0
* <== Total: 3
*/
//子查詢
@Test
void test1(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.inSql("id","select id from user where id>17");
List<Object> objects = userMapper.selectObjs(wrapper);
objects.forEach(System.out::println);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/162626.html
標籤:其他
