MyBatisPlus(二)

查詢操作

// 測(cè)試查詢
@Test
public void testSelectById(){
User user = userMapper.selectById(1L);
System.out.println(user);
}
// 測(cè)試批量查詢!
@Test
public void testSelectByBatchId(){
List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
users.forEach(System.out::println);
}
// 按條件查詢之一使用map操作
@Test
public void testSelectByBatchIds(){
HashMap<String, Object> map = new HashMap<>();
// 自定義要查詢
map.put("name","狂神說Java");
map.put("age",3);
List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}

分頁查詢

分頁在網(wǎng)站使用的十分之多!
1、原始的 limit 進(jìn)行分頁
2、pageHelper 第三方插件
3、MP 其實(shí)也內(nèi)置了分頁插件!

如何使用!

1、配置攔截器組件即可

// 分頁插件
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}

2、直接使用Page對(duì)象即可!

// 測(cè)試分頁查詢
@Test
public void testPage(){
// 參數(shù)一:當(dāng)前頁
// 參數(shù)二:頁面大小
// 使用了分頁插件之后,所有的分頁操作也變得簡單的!
Page<User> page = new Page<>(2,5);
userMapper.selectPage(page,null);
page.getRecords().forEach(System.out::println);
System.out.println(page.getTotal());
}

刪除操作

1、根據(jù) id 刪除記錄

// 測(cè)試刪除
@Test
public void testDeleteById(){
userMapper.deleteById(1240620674645544965L);
}
// 通過id批量刪除
@Test
public void testDeleteBatchId(){
userMapper.deleteBatchIds(Arrays.asList(1240620674645544961L,124062067464554496
2L));
}
// 通過map刪除
@Test
public void testDeleteMap(){
HashMap<String, Object> map = new HashMap<>();
map.put("name","狂神說Java");
userMapper.deleteByMap(map);
}

我們?cè)诠そM中會(huì)遇到一些問題:邏輯刪除!

邏輯刪除

物理刪除 :從數(shù)據(jù)庫中直接移除
邏輯刪除 :再數(shù)據(jù)庫中沒有被移除,而是通過一個(gè)變量來讓他失效! deleted = 0 => deleted = 1

管理員可以查看被刪除的記錄!防止數(shù)據(jù)的丟失,類似于回收站!
測(cè)試一下:
1、在數(shù)據(jù)表中增加一個(gè) deleted 字段


微信截圖_20200513142052.png

2、實(shí)體類中增加屬性

@TableLogic //邏輯刪除
private Integer deleted;

3、配置!

// 邏輯刪除組件!
@Bean
public ISqlInjector sqlInjector() {
return new LogicSqlInjector();
}
# 配置邏輯刪除
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0

4、測(cè)試一下刪除!


微信截圖_20200513142306.png

微信截圖_20200513142324.png

性能分析插件

我們?cè)谄綍r(shí)的開發(fā)中,會(huì)遇到一些慢sql。測(cè)試! druid,,,,,
作用:性能分析攔截器,用于輸出每條 SQL 語句及其執(zhí)行時(shí)間
MP也提供性能分析插件,如果超過這個(gè)時(shí)間就停止運(yùn)行!

1、導(dǎo)入插件

/**
* SQL執(zhí)行效率插件
*/
@Bean
@Profile({"dev","test"})// 設(shè)置 dev test 環(huán)境開啟,保證我們的效率
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
performanceInterceptor.setMaxTime(100); // ms設(shè)置sql執(zhí)行的最大時(shí)間,如果超過了則不執(zhí)行
performanceInterceptor.setFormat(true); // 是否格式化代碼
return performanceInterceptor;
}

記住,要在SpringBoot中配置環(huán)境為dev或者 test 環(huán)境!
2、測(cè)試使用!

@Test
void contextLoads() {
// 參數(shù)是一個(gè) Wrapper ,條件構(gòu)造器,這里我們先不用 null
// 查詢?nèi)坑脩?List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
微信截圖_20200513142559.png

條件構(gòu)造器

十分重要:Wrapper
我們寫一些復(fù)雜的sql就可以使用它來替代!
1、測(cè)試一,記住查看輸出的SQL進(jìn)行分析

@Test
void contextLoads() {
// 查詢name不為空的用戶,并且郵箱不為空的用戶,年齡大于等于12
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper
.isNotNull("name")
.isNotNull("email")
.ge("age",12);
userMapper.selectList(wrapper).forEach(System.out::println); // 和我們剛才學(xué)習(xí)的map對(duì)比一下
}

2、測(cè)試二,記住查看輸出的SQL進(jìn)行分析

@Test
void test2(){
// 查詢名字狂神說
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name","狂神說");
User user = userMapper.selectOne(wrapper); // 查詢一個(gè)數(shù)據(jù),出現(xiàn)多個(gè)結(jié)果使用List或者 Map
System.out.println(user);
}

3、測(cè)試三,記住查看輸出的SQL進(jìn)行分析

@Test
void test3(){
// 查詢年齡在 20 ~ 30 歲之間的用戶
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.between("age",20,30); // 區(qū)間
Integer count = userMapper.selectCount(wrapper);// 查詢結(jié)果數(shù)
System.out.println(count);
}

4、測(cè)試四,記住查看輸出的SQL進(jìn)行分析

// 模糊查詢
@Test
void test4(){
// 查詢年齡在 20 ~ 30 歲之間的用戶
QueryWrapper<User> wrapper = new QueryWrapper<>();
// 左和右 t%
wrapper
.notLike("name","e")
.likeRight("email","t");
List<Map<String, Object>> maps = userMapper.selectMaps(wrapper);
maps.forEach(System.out::println);
}

5、測(cè)試五

// 模糊查詢
@Test
void test5(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
// id 在子查詢中查出來
wrapper.inSql("id","select id from user where id<3");
List<Object> objects = userMapper.selectObjs(wrapper);
objects.forEach(System.out::println);
}

6、測(cè)試六

//測(cè)試六
@Test
void test6(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
// 通過id進(jìn)行排序
wrapper.orderByAsc("id");
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}

代碼自動(dòng)生成器

dao、pojo、service、controller都給我自己去編寫完成!
AutoGenerator 是 MyBatis-Plus 的代碼生成器,通過 AutoGenerator 可以快速生成 Entity、
Mapper、Mapper XML、Service、Controller 等各個(gè)模塊的代碼,極大的提升了開發(fā)效率。
測(cè)試:

package com.kuang;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.ArrayList;
// 代碼自動(dòng)生成器
public class KuangCode {
public static void main(String[] args) {
// 需要構(gòu)建一個(gè) 代碼自動(dòng)生成器 對(duì)象
AutoGenerator mpg = new AutoGenerator();
// 配置策略
// 1、全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath+"/src/main/java");
gc.setAuthor("狂神說");
gc.setOpen(false);
gc.setFileOverride(false); // 是否覆蓋
gc.setServiceName("%sService"); // 去Service的I前綴
gc.setIdType(IdType.ID_WORKER);
gc.setDateType(DateType.ONLY_DATE);
gc.setSwagger2(true);
mpg.setGlobalConfig(gc);
//2、設(shè)置數(shù)據(jù)源
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/kuang_community?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
dsc.setDbType(DbType.MYSQL);
mpg.setDataSource(dsc);
//3、包的配置
PackageConfig pc = new PackageConfig();
pc.setModuleName("blog");
pc.setParent("com.kuang");
pc.setEntity("entity");
pc.setMapper("mapper");
pc.setService("service");
pc.setController("controller");
mpg.setPackageInfo(pc);
//4、策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("blog_tags","course","links","sys_settings","user_record","user_say"); // 設(shè)置要映射的表名
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true); // 自動(dòng)lombok;
strategy.setLogicDeleteFieldName("deleted");
// 自動(dòng)填充配置
TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);
TableFill gmtModified = new TableFill("gmt_modified",
FieldFill.INSERT_UPDATE);
ArrayList<TableFill> tableFills = new ArrayList<>();
tableFills.add(gmtCreate);
tableFills.add(gmtModified);
strategy.setTableFillList(tableFills);
// 樂觀鎖
strategy.setVersionFieldName("version");
strategy.setRestControllerStyle(true);
strategy.setControllerMappingHyphenStyle(true); //localhost:8080/hello_id_2
mpg.setStrategy(strategy);
mpg.execute(); //執(zhí)行
}
}
微信截圖_20200513144154.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容