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