MyBatisPlus中CRUD使用方法詳解
一、insert
1.插入操作
public class CRUDTests { @Autowired private UserMapper userMapper; @Test public void testInsert(){ User user = new User(); user.setName("Helen"); user.setAge(18); user.setEmail("55317332@qq.com"); int result = userMapper.insert(user); System.out.println(result); //影響的行數(shù) System.out.println(user); //id自動(dòng)回填 } }
2.主鍵策略
要想主鍵自增需要配置如下主鍵策略
需要在創(chuàng)建數(shù)據(jù)表的時(shí)候設(shè)置主鍵自增
實(shí)體字段中配置 @TableId(type = IdType.AUTO)
@TableId(type = IdType.AUTO) private Long id;
其它主鍵策略:分析 IdType 源碼可知
public enum IdType { /** * 數(shù)據(jù)庫(kù)ID自增 */ AUTO(0), /** * 該類(lèi)型為未設(shè)置主鍵類(lèi)型 */ NONE(1), /** * 用戶(hù)輸入ID * 該類(lèi)型可以通過(guò)自己注冊(cè)自動(dòng)填充插件進(jìn)行填充 */ INPUT(2), /** * 全局唯一ID */ ASSIGN_ID(3), /** * 全局唯一ID (UUID) */ ASSIGN_UUID(4), /** @deprecated */ @Deprecated ID_WORKER(3), /** @deprecated */ @Deprecated ID_WORKER_STR(3), /** @deprecated */ @Deprecated UUID(4); private final int key; private IdType(int key) { this.key = key; } public int getKey() { return this.key; } }
二、update
1.根據(jù)Id更新操作
注意:update時(shí)生成的sql自動(dòng)是動(dòng)態(tài)sql:UPDATE user SET age=? WHERE id=?
@Test public void testUpdateById(){ User user = new User(); user.setId(1L); user.setAge(28); int result = userMapper.updateById(user); System.out.println(result); }
2.自動(dòng)填充
項(xiàng)目中經(jīng)常會(huì)遇到一些數(shù)據(jù),每次都使用相同的方式填充,例如記錄的創(chuàng)建時(shí)間,更新時(shí)間等。
我們可以使用MyBatis Plus的自動(dòng)填充功能,完成這些字段的賦值工作:
(1)數(shù)據(jù)庫(kù)表中添加自動(dòng)填充字段
在User表中添加datetime類(lèi)型的新的字段 create_time、update_time
(2)實(shí)體上添加注解(@TableField注解標(biāo)記對(duì)哪些字段,在什么時(shí)候進(jìn)行填充)
@Data public class User { ...... @TableField(fill = FieldFill.INSERT) private Date createTime; //@TableField(fill = FieldFill.UPDATE) @TableField(fill = FieldFill.INSERT_UPDATE) private Date updateTime; }
(3)實(shí)現(xiàn)元對(duì)象處理器接口(在這個(gè)接口中指定對(duì)這些字段填充的數(shù)據(jù)時(shí)什么?)
注意:不要忘記添加 @Component 注解
@Component public class MyMetaObjectHandler implements MetaObjectHandler { @Override public void insertFill(MetaObject metaObject) { this.setFieldValByName("createTime", new Date(), metaObject); this.setFieldValByName("updateTime", new Date(), metaObject); } @Override public void updateFill(MetaObject metaObject) { this.setFieldValByName("updateTime", new Date(), metaObject); } }
3.樂(lè)觀鎖
主要適用場(chǎng)景:當(dāng)要更新一條記錄的時(shí)候,希望這條記錄沒(méi)有被別人更新,也就是說(shuō)實(shí)現(xiàn)線程安全的數(shù)據(jù)更新
樂(lè)觀鎖實(shí)現(xiàn)方式:
- 取出記錄時(shí),獲取當(dāng)前version
- 更新時(shí),帶上這個(gè)version
- 執(zhí)行更新時(shí), set version = newVersion where version = oldVersion
- 如果version不對(duì),就更新失敗
(1)數(shù)據(jù)庫(kù)中添加version字段
ALTER TABLE `user` ADD COLUMN `version` INT
(2)實(shí)體類(lèi)添加version字段
并添加 @Version 注解
@Version @TableField(fill = FieldFill.INSERT) private Integer version;
(3)元對(duì)象處理器接口添加version的insert默認(rèn)值
@Override public void insertFill(MetaObject metaObject) { ...... this.setFieldValByName("version", 1, metaObject); }
特別說(shuō)明:
支持的數(shù)據(jù)類(lèi)型只有 int,Integer,long,Long,Date,Timestamp,LocalDateTime
整數(shù)類(lèi)型下 newVersion = oldVersion + 1
newVersion 會(huì)回寫(xiě)到 entity 中
僅支持 updateById(id) 與 update(entity, wrapper) 方法
在 update(entity, wrapper) 方法下, wrapper 不能復(fù)用!!!
(4)在 MybatisPlusConfig 中注冊(cè) Bean
創(chuàng)建配置類(lèi)
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 //該注解,目前沒(méi)有啥用[自我] @Configuration @MapperScan("com.atguigu.mybatis_plus.mapper") //該注解,目前沒(méi)有啥用[自我] public class MybatisPlusConfig { /** * 樂(lè)觀鎖插件 */ @Bean public OptimisticLockerInterceptor optimisticLockerInterceptor() { return new OptimisticLockerInterceptor(); } }
(5)測(cè)試樂(lè)觀鎖可以修改成功
測(cè)試后分析打印的sql語(yǔ)句,將version的數(shù)值進(jìn)行了加1操作
/** * 測(cè)試 樂(lè)觀鎖插件 */ @Test public void testOptimisticLocker() { //查詢(xún) User user = userMapper.selectById(1L); //修改數(shù)據(jù) user.setName("Helen Yao"); user.setEmail("helen@qq.com"); //執(zhí)行更新 userMapper.updateById(user); }
(5)測(cè)試樂(lè)觀鎖修改失敗
/** * 測(cè)試樂(lè)觀鎖插件 失敗 */ @Test public void testOptimisticLockerFail() { //查詢(xún) User user = userMapper.selectById(1L); //修改數(shù)據(jù) user.setName("Helen Yao1"); user.setEmail("helen@qq.com1"); //模擬取出數(shù)據(jù)后,數(shù)據(jù)庫(kù)中version實(shí)際數(shù)據(jù)比取出的值大,即已被其它線程修改并更新了version user.setVersion(user.getVersion() - 1); //執(zhí)行更新 userMapper.updateById(user); }
三、select
1.根據(jù)id查詢(xún)記錄
@Test public void testSelectById(){ User user = userMapper.selectById(1L); System.out.println(user); }
2.通過(guò)多個(gè)id批量查詢(xún)
完成了動(dòng)態(tài)sql的foreach的功能
@Test public void testSelectBatchIds(){ List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3)); users.forEach(System.out::println); }
3.簡(jiǎn)單的條件查詢(xún)
通過(guò)map封裝查詢(xún)條件
@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對(duì)應(yīng)的是數(shù)據(jù)庫(kù)中的列名。例如數(shù)據(jù)庫(kù)user_id,實(shí)體類(lèi)是userId,這時(shí)map的key需要填寫(xiě)user_id
4.分頁(yè)
MyBatis Plus自帶分頁(yè)插件,只要簡(jiǎn)單的配置即可實(shí)現(xiàn)分頁(yè)功能
(1)創(chuàng)建配置類(lèi)
此時(shí)可以刪除主類(lèi)中的 @MapperScan 掃描注解[也可以用主類(lèi)上的@MapperScan注解:
/** * 分頁(yè)插件 */ @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); }
(2)測(cè)試selectPage分頁(yè)
測(cè)試:最終通過(guò)page對(duì)象獲取相關(guān)數(shù)據(jù)
@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()); }
控制臺(tái)sql語(yǔ)句打?。篠ELECT id,name,age,email,create_time,update_time FROM user LIMIT 0,5
(3)測(cè)試selectMapsPage分頁(yè):結(jié)果集是Map
@Test public void testSelectMapsPage() { //Page不需要泛型 Page<Map<String, Object>> page = new Page<>(1, 5); Page<Map<String, Object>> pageParam = userMapper.selectMapsPage(page, null); List<Map<String, Object>> records = pageParam.getRecords(); records.forEach(System.out::println); System.out.println(pageParam.getCurrent()); System.out.println(pageParam.getPages()); System.out.println(pageParam.getSize()); System.out.println(pageParam.getTotal()); System.out.println(pageParam.hasNext()); System.out.println(pageParam.hasPrevious()); }
四、delete
1.根據(jù)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.簡(jiǎn)單的條件查詢(xún)刪除
@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.邏輯刪除
- 物理刪除:真實(shí)刪除,將對(duì)應(yīng)數(shù)據(jù)從數(shù)據(jù)庫(kù)中刪除,之后查詢(xún)不到此條被刪除數(shù)據(jù)
- 邏輯刪除:假刪除,將對(duì)應(yīng)數(shù)據(jù)中代表是否被刪除字段狀態(tài)修改為“被刪除狀態(tài)”,之后在數(shù)據(jù)庫(kù)中仍舊能看到此條數(shù)據(jù)記錄
(1)數(shù)據(jù)庫(kù)中添加 deleted字段
ALTER TABLE `user` ADD COLUMN `deleted` boolean
(2)實(shí)體類(lèi)添加deleted 字段
并加上 @TableLogic 注解 和 @TableField(fill = FieldFill.INSERT) 注解
@TableLogic @TableField(fill = FieldFill.INSERT) private Integer deleted;
(3)元對(duì)象處理器接口添加deleted的insert默認(rèn)值
@Override public void insertFill(MetaObject metaObject) { ...... this.setFieldValByName("deleted", 0, metaObject); }
(4)application.properties 加入配置
此為默認(rèn)值,如果你的默認(rèn)值和mp默認(rèn)的一樣,該配置可無(wú)
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
(5)測(cè)試邏輯刪除
- 測(cè)試后發(fā)現(xiàn),數(shù)據(jù)并沒(méi)有被刪除,deleted字段的值由0變成了1
- 測(cè)試后分析打印的sql語(yǔ)句,是一條update
- 注意:被刪除數(shù)據(jù)的deleted 字段的值必須是 0,才能被選取出來(lái)執(zhí)行邏輯刪除的操作
/** * 測(cè)試 邏輯刪除 */ @Test public void testLogicDelete() { int result = userMapper.deleteById(1L); System.out.println(result); }
(7)測(cè)試邏輯刪除后的查詢(xún)
MyBatis Plus中查詢(xún)操作也會(huì)自動(dòng)添加邏輯刪除字段的判斷
/** * 測(cè)試 邏輯刪除后的查詢(xún): * 不包括被邏輯刪除的記錄 */ @Test public void testLogicDeleteSelect() { User user = new User(); List<User> users = userMapper.selectList(null); users.forEach(System.out::println); }
測(cè)試后分析打印的sql語(yǔ)句,包含 WHERE deleted=0
SELECT id,name,age,email,create_time,update_time,deleted FROM user WHERE deleted=0
到此這篇關(guān)于MyBatisPlus中CRUD使用方法詳解的文章就介紹到這了,更多相關(guān)MyBatisPlus CRUD內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
將java普通項(xiàng)目打包成exe可執(zhí)行文件的步驟記錄
將JAVA代碼打包為exe文件,會(huì)讓程序運(yùn)行更加方便,這篇文章主要給大家介紹了關(guān)于將java普通項(xiàng)目打包成exe可執(zhí)行文件的相關(guān)資料,需要的朋友可以參考下2021-07-07Java Web開(kāi)發(fā)中過(guò)濾器和監(jiān)聽(tīng)器使用詳解
這篇文章主要為大家詳細(xì)介紹了Java中的過(guò)濾器Filter和監(jiān)聽(tīng)器Listener的使用以及二者的區(qū)別,文中的示例代碼講解詳細(xì),需要的可以參考一下2022-10-10SpringBoot實(shí)現(xiàn)發(fā)送QQ郵件的示例代碼
這篇文章主要介紹了SpringBoot如何實(shí)現(xiàn)發(fā)送QQ郵件功能,本文通過(guò)實(shí)例圖文相結(jié)合給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-09-09解決RabbitMq消息隊(duì)列Qos?Prefetch消息堵塞問(wèn)題
這篇文章主要為大家介紹了關(guān)于如何解決解決RabbitMq?Qos?Prefetch消息堵塞的問(wèn)題分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助2022-01-01Springboot允許logger.debug輸出日志方式
這篇文章主要介紹了Springboot允許logger.debug輸出日志方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06Java基礎(chǔ)學(xué)習(xí)筆記之?dāng)?shù)組詳解
這篇文章主要介紹了Java基礎(chǔ)學(xué)習(xí)筆記之?dāng)?shù)組,結(jié)合實(shí)例形式詳細(xì)分析了java的基本概念、定義、迭代、輸出、反轉(zhuǎn)、排序等常用操作技巧,需要的朋友可以參考下2019-08-08關(guān)于spring中單例Bean引用原型Bean產(chǎn)生的問(wèn)題及解決
這篇文章主要介紹了關(guān)于spring中單例Bean引用原型Bean產(chǎn)生的問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06