SpringBoot框架中Mybatis-plus的簡(jiǎn)單使用操作匯總
Mybatis-plus
官網(wǎng)地址:https://baomidou.com/
配置mysql
在配置文件連接mysql
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/cat_house?serverTimezone=GMT%2B8 spring.datasource.username=username spring.datasource.password=password # mybatis日志(控制臺(tái)能顯示SQL語(yǔ)句) mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
Mybatis-plus使用方式
依賴導(dǎo)入
<!-- mybatis驅(qū)動(dòng) --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.0.5</version> </dependency> <!-- 數(shù)據(jù)庫(kù)驅(qū)動(dòng) --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
lombok依賴導(dǎo)入
<!-- lombok用來(lái)簡(jiǎn)化實(shí)體類 --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency>
Mybatis-plus實(shí)現(xiàn)簡(jiǎn)單的CURD操作
準(zhǔn)備表格(數(shù)據(jù)庫(kù)有相應(yīng)的表格)
準(zhǔn)備實(shí)體(實(shí)體文件夾中有相應(yīng)的實(shí)體類)
package com.xsha.boot.entity; import lombok.Data; @Data public class Topic { private int id; private String title; private String time; private int count; private int version; }
準(zhǔn)備映射文件(映射文件夾中有相應(yīng)的映射接口)
package com.xsha.boot.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.xsha.boot.entity.Topic; import org.springframework.stereotype.Repository; @Repository public interface TopicMapper extends BaseMapper<Topic> { }
測(cè)試操作(在test類中進(jìn)行簡(jiǎn)單的單元測(cè)試)
package com.xsha.boot; import com.xsha.boot.entity.Topic; import com.xsha.boot.mapper.TopicMapper; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.List; @SpringBootTest public class MainApplicationTest { @Autowired // 可在指定的接口上添加注解Repository,就不會(huì)爆紅了 private TopicMapper topicMapper; // 查詢所有數(shù)據(jù) @Test public void findAll() { List<Topic> topics = topicMapper.selectList(null); for (int i = 0; i < topics.size(); i++) { System.out.println(topics.get(i)); } } // 添加操作 public void addTopic() { // SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); // Date date = new Date(); Topic topic = new Topic(); topic.setTitle("SSM框架整合了哪些主流框架"); // 時(shí)間的添加可以采用mybatis-plus框架實(shí)現(xiàn),可查看Controller中接口實(shí)現(xiàn)和實(shí)體類屬性的注解 // topic.setTime(ft.format(date)); int row = topicMapper.insert(topic); System.out.println("添加的行數(shù):"+row); // 修改操作 public void updateTopic() { topic.setId(20); topic.setCount(10); int row = topicMapper.updateById(topic); System.out.println("修改的行數(shù)"+row); }
Mybatis-plus自動(dòng)填充策略
主鍵自動(dòng)填充
// 可以在id屬性上添加TableId注解可以修改id唯一鍵值的策略(自動(dòng)填充),如@TableId(type=IdType.AUTO) // @TableId(type=IdType.ID_WORKER) 生成19位唯一數(shù)字的鍵值 // @TableId(type=IdType.ID_WORKER_STR) 生成19位唯一字符串的鍵值 private int id;
時(shí)間自動(dòng)填充
實(shí)體類屬性添加注解
// 采用mybatis-plus框架的策略自動(dòng)填充時(shí)間 // @TableField(fill=FieldFill.INSERT) 表示自動(dòng)填充創(chuàng)建時(shí)間 // @TableField(fill=FieldFill.INSERT_UPDATE) 表示自動(dòng)填充更新時(shí)間 @TableField(fill = FieldFill.INSERT) private String time;
Controller類繼承接口實(shí)現(xiàn)時(shí)間自動(dòng)填充方法
package com.xsha.boot.controller; import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; import org.apache.ibatis.reflection.MetaObject; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.Date; @Component public class MyMetaObjectController implements MetaObjectHandler { // 使用mybatis-plus實(shí)現(xiàn)添加操作,這個(gè)方法自動(dòng)調(diào)用 @Override public void insertFill(MetaObject metaObject) { SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); Date date = new Date(); // 第一個(gè)參數(shù)不是表格的字段名稱,而是實(shí)體類的屬性名稱 this.setFieldValByName("time", ft.format(date), metaObject); } // 使用mybatis-plus實(shí)現(xiàn)更新操作,這個(gè)方法自動(dòng)調(diào)用 public void updateFill(MetaObject metaObject) { // 更新時(shí)間可根據(jù)需求實(shí)現(xiàn) }
樂(lè)觀鎖的具體實(shí)現(xiàn)
- 表格添加字段version,作為樂(lè)觀鎖版本號(hào)
- 對(duì)應(yīng)實(shí)體類添加版本號(hào)屬性,并且在屬性上面添加注解Version(baomidou下的Version)
- 在配置類中添加樂(lè)觀鎖插件
@Configuration @MapperScan("com.xsha.boot.mapper") public class MyConfig { // 樂(lè)觀鎖插件 @Bean public OptimisticLockerInterceptor optimisticLockerInterceptor() { return new OptimisticLockerInterceptor(); } }
Mybatis-plus查詢操作(簡(jiǎn)單)
// 單個(gè)id查詢 @Test public void selectTopic() { Topic topic = topicMapper.selectById(20); System.out.println(topic); } // 多個(gè)id批量查詢 @Test public void selectTopics() { List<Topic> topics = topicMapper.selectBatchIds(Arrays.asList(1, 2, 3, 4)); for (int i = 0; i < topics.size(); i++) { System.out.println(topics.get(i)); } }
Mybatis-plus實(shí)現(xiàn)分頁(yè)操作
在配置類中配置分頁(yè)插件
// 分頁(yè)插件 @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); }
編寫(xiě)分頁(yè)代碼
// 分頁(yè)查詢 @Test public void selectByPage() { // 1.創(chuàng)建page對(duì)象,傳遞當(dāng)前頁(yè)和每頁(yè)記錄數(shù)的兩個(gè)參數(shù) Page<Topic> page = new Page<>(1, 3); // 2.調(diào)用mybatis-plus分頁(yè)查詢的方法,把分頁(yè)所有的數(shù)據(jù)封裝到page對(duì)象里面,第二個(gè)參數(shù)是條件 topicMapper.selectPage(page, null); // 3.通過(guò)page對(duì)象獲取分頁(yè)數(shù)據(jù) System.out.println(page.getCurrent()); // 當(dāng)前頁(yè) System.out.println(page.getRecords()); // 每頁(yè)數(shù)據(jù)list集合 System.out.println(page.getSize()); // 每頁(yè)顯示記錄數(shù) System.out.println(page.getTotal()); // 總記錄數(shù) System.out.println(page.getPages()); // 總頁(yè)數(shù) System.out.println(page.hasNext()); // 是否有下一頁(yè) System.out.println(page.hasPrevious()); // 是否有上一頁(yè) }
Mybatis-plus刪除操作(簡(jiǎn)單)
物理刪除
// 單個(gè)id刪除 @Test public void deleteTopic() { int row = topicMapper.deleteById(20); System.out.println(row); } // 多個(gè)id批量刪除 @Test public void deleteTopics() { int rows = topicMapper.deleteBatchIds(Arrays.asList(1, 2, 3, 4)); System.out.println(rows); }
邏輯刪除
表格中添加標(biāo)志位字段,供邏輯刪除使用
表格字段設(shè)置默認(rèn)值,就不能使用mybatis-plus的自動(dòng)填充使用mybatis-plus的自動(dòng)填充
使用mybatis-plus的自動(dòng)填充時(shí),在實(shí)體類屬性上添加TableLogic注解
@TableLogic private int delete;
在配置類中配置邏輯刪除插件
// 邏輯刪除插件 @Bean public ISqlInjector sqlInjector() { return new LogicSqlInjector(); }
在配置文件中添加邏輯刪除與否的默認(rèn)值(可有可無(wú))
# 邏輯刪除與否的默認(rèn)值 mybatis-plus.global-config.db-config.logic-delete-value=1 mybatis-plus.global-config.db-config.logic-not-delete-value=0
代碼編寫(xiě)
// 邏輯刪除 @Test public void logicDeleteTopic() { int row = topicMapper.deleteById(21); System.out.println(row); }
注意:采用mybatis-plus的邏輯刪除方式時(shí),之后查詢數(shù)據(jù)時(shí)就不會(huì)包括邏輯刪除的數(shù)據(jù)
性能分析
在配置類中添加性能分析插件
/** * SQL執(zhí)行性能分析插件 * 開(kāi)發(fā)環(huán)境使用,線上不推薦。maxTime指的是sql最大執(zhí)行時(shí)長(zhǎng) * * 三種環(huán)境:dev開(kāi)發(fā)環(huán)境、test測(cè)試環(huán)境、prod生成環(huán)境 * @return */ @Bean @Profile({"dev", "test"}) // 設(shè)置dev,test的環(huán)境開(kāi)啟 public PerformanceInterceptor performanceInterceptor() { PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor(); performanceInterceptor.setMaxTime(100); // 數(shù)值單位為毫秒ms performanceInterceptor.setFormat(true); return performanceInterceptor; }
在配置文件中配置環(huán)境
# 環(huán)境設(shè)置:dev test prod spring.profiles.active=dev
Mybatis-plus實(shí)現(xiàn)復(fù)雜條件查詢
使用QueryWrapper類對(duì)象構(gòu)造條件(還有其他的)
// mybatis-plus實(shí)現(xiàn)復(fù)雜查詢 @Test public void querySelect() { // 1.創(chuàng)建QueryWrapper對(duì)象 QueryWrapper<Topic> queryWrapper = new QueryWrapper<>(); // 2.通過(guò)QueryWrapper設(shè)置條件 // ge(>=)、gt(>)、le(<=)、lt(<) queryWrapper.ge("count", 3); List<Topic> topics1 = topicMapper.selectList(queryWrapper); System.out.println("FIRST"); System.out.println(topics1); // eq(==)、ne(!=) queryWrapper.ne("deleted", 0); List<Topic> topics2 = topicMapper.selectList(queryWrapper); System.out.println("SECOND"); System.out.println(topics2); // between(在···和···之間) queryWrapper.between("time", "2021-10-12 07:05:29.546779", "2021-10-27 15:02:09.458571"); List<Topic> topics3 = topicMapper.selectList(queryWrapper); System.out.println("THIRD"); System.out.println(topics3); // like(模糊查詢) queryWrapper.like("title", "SSM"); List<Topic> topics4 = topicMapper.selectList(queryWrapper); System.out.println("FORTH"); System.out.println(topics4); // 排序 orderByDesc orderByAsc queryWrapper.orderByDesc("count"); List<Topic> topics5 = topicMapper.selectList(queryWrapper); System.out.println("FIFTH"); System.out.println(topics5); // 指定要查詢的列 last拼接sql語(yǔ)句 queryWrapper.select("id", "title", "count"); queryWrapper.last("limit 2"); List<Topic> topics6 = topicMapper.selectList(queryWrapper); System.out.println("SIXTH"); System.out.println(topics6); }
到此這篇關(guān)于SpringBoot框架中Mybatis-plus的簡(jiǎn)單使用的文章就介紹到這了,更多相關(guān)SpringBoot Mybatis-plus使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java fastjson解析json字符串實(shí)現(xiàn)過(guò)程解析
這篇文章主要介紹了Java fastjson解析json字符串實(shí)現(xiàn)過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-10-10springboot的yml配置文件通過(guò)db2的方式整合mysql的教程
這篇文章主要介紹了springboot的yml配置文件通過(guò)db2的方式整合mysql的教程,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-09-09Java詳解如何將excel數(shù)據(jù)轉(zhuǎn)為樹(shù)形
在平常的辦公工作中,excel數(shù)據(jù)的操作是最常見(jiàn)的需求,今天就來(lái)看一下通過(guò)Java如何來(lái)實(shí)現(xiàn)將excel數(shù)據(jù)轉(zhuǎn)為樹(shù)形,感興趣的朋友可以了解下2022-08-08Java中使用BigDecimal進(jìn)行精確運(yùn)算
這篇文章主要介紹了Java中使用BigDecimal進(jìn)行精確運(yùn)算的方法,非常不錯(cuò),需要的朋友參考下2017-02-02JAVA中String介紹及常見(jiàn)面試題小結(jié)
這篇文章主要介紹了JAVA中String介紹及常見(jiàn)面試題,在java面試中經(jīng)常會(huì)被面試官問(wèn)到,小編通過(guò)實(shí)例代碼相結(jié)合給大家詳細(xì)介紹,需要的朋友可以參考下2020-02-02