SpringBoot框架中Mybatis-plus的簡單使用操作匯總
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語句) 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ù)庫驅(qū)動(dòng) -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>lombok依賴導(dǎo)入
<!-- lombok用來簡化實(shí)體類 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>Mybatis-plus實(shí)現(xiàn)簡單的CURD操作
準(zhǔn)備表格(數(shù)據(jù)庫有相應(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)行簡單的單元測(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)
}樂觀鎖的具體實(shí)現(xiàn)
- 表格添加字段version,作為樂觀鎖版本號(hào)
- 對(duì)應(yīng)實(shí)體類添加版本號(hào)屬性,并且在屬性上面添加注解Version(baomidou下的Version)
- 在配置類中添加樂觀鎖插件
@Configuration
@MapperScan("com.xsha.boot.mapper")
public class MyConfig {
// 樂觀鎖插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
}Mybatis-plus查詢操作(簡單)
// 單個(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)分頁操作
在配置類中配置分頁插件
// 分頁插件
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}編寫分頁代碼
// 分頁查詢
@Test
public void selectByPage() {
// 1.創(chuàng)建page對(duì)象,傳遞當(dāng)前頁和每頁記錄數(shù)的兩個(gè)參數(shù)
Page<Topic> page = new Page<>(1, 3);
// 2.調(diào)用mybatis-plus分頁查詢的方法,把分頁所有的數(shù)據(jù)封裝到page對(duì)象里面,第二個(gè)參數(shù)是條件
topicMapper.selectPage(page, null);
// 3.通過page對(duì)象獲取分頁數(shù)據(jù)
System.out.println(page.getCurrent()); // 當(dāng)前頁
System.out.println(page.getRecords()); // 每頁數(shù)據(jù)list集合
System.out.println(page.getSize()); // 每頁顯示記錄數(shù)
System.out.println(page.getTotal()); // 總記錄數(shù)
System.out.println(page.getPages()); // 總頁數(shù)
System.out.println(page.hasNext()); // 是否有下一頁
System.out.println(page.hasPrevious()); // 是否有上一頁
}Mybatis-plus刪除操作(簡單)
物理刪除
// 單個(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)值(可有可無)
# 邏輯刪除與否的默認(rèn)值 mybatis-plus.global-config.db-config.logic-delete-value=1 mybatis-plus.global-config.db-config.logic-not-delete-value=0
代碼編寫
// 邏輯刪除
@Test
public void logicDeleteTopic() {
int row = topicMapper.deleteById(21);
System.out.println(row);
}注意:采用mybatis-plus的邏輯刪除方式時(shí),之后查詢數(shù)據(jù)時(shí)就不會(huì)包括邏輯刪除的數(shù)據(jù)
性能分析
在配置類中添加性能分析插件
/**
* SQL執(zhí)行性能分析插件
* 開發(fā)環(huán)境使用,線上不推薦。maxTime指的是sql最大執(zhí)行時(shí)長
*
* 三種環(huán)境:dev開發(fā)環(huán)境、test測(cè)試環(huán)境、prod生成環(huán)境
* @return
*/
@Bean
@Profile({"dev", "test"}) // 設(shè)置dev,test的環(huán)境開啟
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.通過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語句
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的簡單使用的文章就介紹到這了,更多相關(guān)SpringBoot Mybatis-plus使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java數(shù)據(jù)結(jié)構(gòu)排序算法之歸并排序詳解
這篇文章主要介紹了java數(shù)據(jù)結(jié)構(gòu)排序算法之歸并排序,結(jié)合具體實(shí)例形式詳細(xì)分析了歸并排序的原理、實(shí)現(xiàn)技巧與相關(guān)注意事項(xiàng),需要的朋友可以參考下2017-05-05
springboot的緩存技術(shù)的實(shí)現(xiàn)
這篇文章主要介紹了springboot的緩存技術(shù)的實(shí)現(xiàn),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-05-05
scala中的隱式類型轉(zhuǎn)換的實(shí)現(xiàn)
這篇文章主要介紹了scala中的隱式類型轉(zhuǎn)換的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06
springboot @ConfigurationProperties和@PropertySource的區(qū)別
這篇文章主要介紹了springboot @ConfigurationProperties和@PropertySource的區(qū)別,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06
Java利用apache ftp工具實(shí)現(xiàn)文件上傳下載和刪除功能
這篇文章主要為大家詳細(xì)介紹了Java利用apache ftp工具實(shí)現(xiàn)文件上傳下載、刪除功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-06-06

