一、insert
1、插入操作
@RunWith(SpringRunner.class)
@SpringBootTest
public class CRUDTests {
@Autowired
private UserMapper userMapper;
@Test
public void testInsert(){
User user = new User();
user.setName("Helen");
user.setAge(18);
user.setEmail("[email protected]");
int result = userMapper.insert(user);
System.out.println(result); //影響的行數
System.out.println(user); //id自動回填
}
}
注意: 資料庫插入id值默認為:全域唯一id

2、主鍵策略
(1)ID_WORKER
MyBatis-Plus默認的主鍵策略是:ID_WORKER 全域唯一ID
參考資料:分布式系統唯一ID生成方案匯總:https://www.cnblogs.com/haoxinyue/p/5208136.html
(2)自增策略
- 要想主鍵自增需要配置如下主鍵策略
- 需要在創建資料表的時候設定主鍵自增
- 物體欄位中配置 @TableId(type = IdType.AUTO)
@TableId(type = IdType.AUTO)
private Long id;
要想影響所有物體的配置,可以設定全域主鍵配置
#全域設定主鍵生成策略
mybatis-plus.global-config.db-config.id-type=auto
其它主鍵策略:分析 IdType 原始碼可知
@Getter
public enum IdType {
/**
* 資料庫ID自增
*/
AUTO(0),
/**
* 該型別為未設定主鍵型別
*/
NONE(1),
/**
* 用戶輸入ID
* 該型別可以通過自己注冊自動填充插件進行填充
*/
INPUT(2),
/* 以下3種型別、只有當插入物件ID 為空,才自動填充, */
/**
* 全域唯一ID (idWorker)
*/
ID_WORKER(3),
/**
* 全域唯一ID (UUID)
*/
UUID(4),
/**
* 字串全域唯一ID (idWorker 的字串表示)
*/
ID_WORKER_STR(5);
private int key;
IdType(int key) {
this.key = key;
}
}
二、update
1、根據Id更新操作
注意: update時生成的sql自動是動態sql: UPDATE user SET age=? WHERE id=?
2、自動填充
專案中經常會遇到一些資料,每次都使用相同的方式填充,例如記錄的創建時間,更新時間等,
我們可以使用MyBatis Plus的自動填充功能,完成這些欄位的賦值作業:
(1)資料庫表中添加自動填充欄位
在User表中添加datetime型別的新的欄位 create_time、update_time
(2)物體上添加注解
@Data
public class User {
......
@TableField(fill = FieldFill.INSERT)
private Date createTime;
//@TableField(fill = FieldFill.UPDATE)
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
}
(3)實作元物件處理器介面
注意:不要忘記添加 @Component 注解
package com.atguigu.mybatisplus.handler;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(MyMetaObjectHandler.class);
@Override
public void insertFill(MetaObject metaObject) {
LOGGER.info("start insert fill ....");
this.setFieldValByName("createTime", new Date(), metaObject);
this.setFieldValByName("updateTime", new Date(), metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
LOGGER.info("start update fill ....");
this.setFieldValByName("updateTime", new Date(), metaObject);
}
}
(4)測驗
3、樂觀鎖
主要適用場景:當要更新一條記錄的時候,希望這條記錄沒有被別人更新,也就是說實作執行緒安全的資料更新
樂觀鎖實作方式:
- 取出記錄時,獲取當前version
- 更新時,帶上這個version
- 執行更新時, set version = newVersion where version = oldVersion
- 如果version不對,就更新失敗
(1)資料庫中添加version欄位
ALTER TABLE `user` ADD COLUMN `version` INT

(2)物體類添加version欄位
并添加 @Version 注解
@Version
@TableField(fill = FieldFill.INSERT)
private Integer version;
(3)元物件處理器介面添加version的insert默認值
@Override
public void insertFill(MetaObject metaObject) {
......
this.setFieldValByName("version", 1, metaObject);
}
特別說明:
- 支持的資料型別只有 int,Integer,long,Long,Date,Timestamp,LocalDateTime
- 整數型別下 newVersion = oldVersion + 1
- newVersion 會回寫到 entity 中
- 僅支持 updateById(id) 與 update(entity, wrapper) 方法
- 在 update(entity, wrapper) 方法下, wrapper 不能復用!!!
(4)在 MybatisPlusConfig 中注冊 Bean
創建配置類
package com.atguigu.mybatisplus.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableTransactionManagement
@Configuration
@MapperScan("com.atguigu.mybatis_plus.mapper")
public class MybatisPlusConfig {
/**
* 樂觀鎖插件
*/
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
}
(5)測驗樂觀鎖可以修改成功
測驗后分析列印的sql陳述句,將version的數值進行了加1操作
/**
* 測驗 樂觀鎖插件
*/
@Test
public void testOptimisticLocker() {
//查詢
User user = userMapper.selectById(1L);
//修改資料
user.setName("Helen Yao");
user.setEmail("[email protected]");
//執行更新
userMapper.updateById(user);
}
(5)測驗樂觀鎖修改失敗
/**
* 測驗樂觀鎖插件 失敗
*/
@Test
public void testOptimisticLockerFail() {
//查詢
User user = userMapper.selectById(1L);
//修改資料
user.setName("Helen Yao1");
user.setEmail("[email protected]");
//模擬取出資料后,資料庫中version實際資料比取出的值大,即已被其它執行緒修改并更新了version
user.setVersion(user.getVersion() - 1);
//執行更新
userMapper.updateById(user);
}
三、select
1、根據id查詢記錄
@Test
public void testSelectById(){
User user = userMapper.selectById(1L);
System.out.println(user);
}
2、通過多個id批量查詢
完成了動態sql的foreach的功能
@Test
public void testSelectBatchIds(){
List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
users.forEach(System.out::println);
}
3、簡單的條件查詢
通過map封裝查詢條件
@Test
public void testSelectByMap(){
HashMap<String, Object> map = new HashMap<>();
map.put("name", "Helen");
map.put("age", 18);
List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}
注意:
map中的key對應的是資料庫中的列名,例如資料庫user_id,物體類是userId,這時map的key需要填寫user_id
4、分頁
MyBatis Plus自帶分頁插件,只要簡單的配置即可實作分頁功能
(1)創建配置類
此時可以洗掉主類中的 @MapperScan 掃描注解
/**
2
* 分頁插件
3
*/
4
@Bean
5
public PaginationInterceptor paginationInterceptor() {
6
return new PaginationInterceptor();
7
}
(2)測驗selectPage分頁
測驗:最終通過page物件獲取相關資料
@Test
public void testSelectPage() {
Page<User> page = new Page<>(1,5);
userMapper.selectPage(page, null);
page.getRecords().forEach(System.out::println);
System.out.println(page.getCurrent());
System.out.println(page.getPages());
System.out.println(page.getSize());
System.out.println(page.getTotal());
System.out.println(page.hasNext());
System.out.println(page.hasPrevious());
}
控制臺sql陳述句列印:SELECT id,name,age,email,create_time,update_time FROM user LIMIT 0,5
(3)測驗selectMapsPage分頁:結果集是Map
@Test
public void testSelectMapsPage() {
Page<User> page = new Page<>(1, 5);
IPage<Map<String, Object>> mapIPage = userMapper.selectMapsPage(page, null);
//注意:此行必須使用 mapIPage 獲取記錄串列,否則會有資料型別轉換錯誤
mapIPage.getRecords().forEach(System.out::println);
System.out.println(page.getCurrent());
System.out.println(page.getPages());
System.out.println(page.getSize());
System.out.println(page.getTotal());
System.out.println(page.hasNext());
System.out.println(page.hasPrevious());
}
四、delete
1、根據id洗掉記錄
@Test
public void testDeleteById(){
int result = userMapper.deleteById(8L);
System.out.println(result);
}
2、批量洗掉
@Test
public void testDeleteBatchIds() {
int result = userMapper.deleteBatchIds(Arrays.asList(8, 9, 10));
System.out.println(result);
}
3、簡單的條件查詢洗掉
@Test
public void testDeleteByMap() {
HashMap<String, Object> map = new HashMap<>();
map.put("name", "Helen");
map.put("age", 18);
int result = userMapper.deleteByMap(map);
System.out.println(result);
}
4、邏輯洗掉
- 物理洗掉:真實洗掉,將對應資料從資料庫中洗掉,之后查詢不到此條被洗掉資料
- 邏輯洗掉:假洗掉,將對應資料中代表是否被洗掉欄位狀態修改為“被洗掉狀態”,之后在資料庫中仍舊能看到此條資料記錄
(1)資料庫中添加 deleted欄位
ALTER TABLE `user` ADD COLUMN `deleted` boolean

(2)物體類添加deleted 欄位
并加上 @TableLogic 注解 和 @TableField(fill = FieldFill.INSERT) 注解
@TableLogic
@TableField(fill = FieldFill.INSERT)
private Integer deleted;
(3)元物件處理器介面添加deleted的insert默認值
@Override
public void insertFill(MetaObject metaObject) {
......
this.setFieldValByName("deleted", 0, metaObject);
}
(4)application.properties 加入配置
此為默認值,如果你的默認值和mp默認的一樣,該配置可無
mybatis-plus.global-config.db-config.logic-delete-value=https://www.cnblogs.com/jadite/p/1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
(5)在 MybatisPlusConfig 中注冊 Bean
@Bean
public ISqlInjector sqlInjector() {
return new LogicSqlInjector();
}
(6)測驗邏輯洗掉
- 測驗后發現,資料并沒有被洗掉,deleted欄位的值由0變成了1
- 測驗后分析列印的sql陳述句,是一條update
- 注意:被洗掉資料的deleted 欄位的值必須是 0,才能被選取出來執行邏輯洗掉的操作
/**
* 測驗 邏輯洗掉
*/
@Test
public void testLogicDelete() {
int result = userMapper.deleteById(1L);
System.out.println(result);
}
(7)測驗邏輯洗掉后的查詢
MyBatis Plus中查詢操作也會自動添加邏輯洗掉欄位的判斷
/**
2
* 測驗 邏輯洗掉后的查詢:
3
* 不包括被邏輯洗掉的記錄
4
*/
@Test
public void testLogicDeleteSelect() {
User user = new User();
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
測驗后分析列印的sql陳述句,包含 WHERE deleted=0
SELECT id,name,age,email,create_time,update_time,deleted FROM user WHERE deleted=0
五、性能分析
性能分析攔截器,用于輸出每條 SQL 陳述句及其執行時間
SQL 性能執行分析,開發環境使用,超過指定時間,停止運行,有助于發現問題
1、配置插件
(1)引數說明
引數:maxTime: SQL 執行最大時長,超過自動停止運行,有助于發現問題,
引數:format: SQL是否格式化,默認false,
(2)在 MybatisPlusConfig 中配置
/**
* SQL 執行性能分析插件
* 開發環境使用,線上不推薦, maxTime 指的是 sql 最大執行時長
*/
@Bean
@Profile({"dev","test"})// 設定 dev test 環境開啟
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
performanceInterceptor.setMaxTime(100);//ms,超過此處設定的ms則sql不執行
performanceInterceptor.setFormat(true);
return performanceInterceptor;
}
(3)Spring Boot 中設定dev環境
#環境設定:dev、test、prod
spring.profiles.active=dev
可以針對各環境新建不同的組態檔application-dev.properties、application-test.properties、application-prod.properties
也可以自定義環境名稱:如test1、test2
2、測驗
(1)常規測驗
/**
* 測驗 性能分析插件
*/
@Test
public void testPerformance() {
User user = new User();
user.setName("我是Helen");
user.setEmail("[email protected]");
user.setAge(18);
userMapper.insert(user);
}

(2)將maxTime 改小之后再次進行測驗
performanceInterceptor.setMaxTime(5);//ms,超過此處設定的ms不執行
如果執行時間過長,則拋出例外:The SQL execution time is too large,

六、其它
如果想進行復雜條件查詢,那么需要使用條件構造器 Wapper,涉及到如下方法
1、delete
2、selectOne
3、selectCount
4、selectList
5、selectMaps
6、selectObjs
7、update
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/507116.html
標籤:Java
上一篇:OpenGL ES EAGLContext 和 EGLContext
下一篇:02-MyBatisPlus入門
