查詢操作
// 測(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","狂神說(shuō)Java");
map.put("age",3);
List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}
分頁(yè)查詢
分頁(yè)在網(wǎng)站使用的十分之多祟印!
1、原始的 limit 進(jìn)行分頁(yè)
2粟害、pageHelper 第三方插件
3蕴忆、MP 其實(shí)也內(nèi)置了分頁(yè)插件!
如何使用悲幅!
1套鹅、配置攔截器組件即可
// 分頁(yè)插件
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
2、直接使用Page對(duì)象即可汰具!
// 測(cè)試分頁(yè)查詢
@Test
public void testPage(){
// 參數(shù)一:當(dāng)前頁(yè)
// 參數(shù)二:頁(yè)面大小
// 使用了分頁(yè)插件之后芋哭,所有的分頁(yè)操作也變得簡(jiǎn)單的!
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);
}
// 通過(guò)id批量刪除
@Test
public void testDeleteBatchId(){
userMapper.deleteBatchIds(Arrays.asList(1240620674645544961L,124062067464554496
2L));
}
// 通過(guò)map刪除
@Test
public void testDeleteMap(){
HashMap<String, Object> map = new HashMap<>();
map.put("name","狂神說(shuō)Java");
userMapper.deleteByMap(map);
}
我們?cè)诠そM中會(huì)遇到一些問(wèn)題:邏輯刪除!
邏輯刪除
物理刪除 :從數(shù)據(jù)庫(kù)中直接移除
邏輯刪除 :再數(shù)據(jù)庫(kù)中沒(méi)有被移除豌习,而是通過(guò)一個(gè)變量來(lái)讓他失效存谎! deleted = 0 => deleted = 1
管理員可以查看被刪除的記錄!防止數(shù)據(jù)的丟失肥隆,類似于回收站既荚!
測(cè)試一下:
1、在數(shù)據(jù)表中增加一個(gè) deleted 字段
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è)試一下刪除凿宾!
性能分析插件
我們?cè)谄綍r(shí)的開(kāi)發(fā)中,會(huì)遇到一些慢sql兼蕊。測(cè)試初厚! druid,,,,,
作用:性能分析攔截器,用于輸出每條 SQL 語(yǔ)句及其執(zhí)行時(shí)間
MP也提供性能分析插件孙技,如果超過(guò)這個(gè)時(shí)間就停止運(yùn)行产禾!
1、導(dǎo)入插件
/**
* SQL執(zhí)行效率插件
*/
@Bean
@Profile({"dev","test"})// 設(shè)置 dev test 環(huán)境開(kāi)啟牵啦,保證我們的效率
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
performanceInterceptor.setMaxTime(100); // ms設(shè)置sql執(zhí)行的最大時(shí)間亚情,如果超過(guò)了則不執(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);
}
條件構(gòu)造器
十分重要:Wrapper
我們寫(xiě)一些復(fù)雜的sql就可以使用它來(lái)替代!
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(){
// 查詢名字狂神說(shuō)
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name","狂神說(shuō)");
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 在子查詢中查出來(lái)
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<>();
// 通過(guò)id進(jìn)行排序
wrapper.orderByAsc("id");
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}
代碼自動(dòng)生成器
dao辜梳、pojo、service泳叠、controller都給我自己去編寫(xiě)完成作瞄!
AutoGenerator 是 MyBatis-Plus 的代碼生成器,通過(guò) AutoGenerator 可以快速生成 Entity危纫、
Mapper宗挥、Mapper XML乌庶、Service、Controller 等各個(gè)模塊的代碼契耿,極大的提升了開(kāi)發(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("狂神說(shuō)");
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);
// 樂(lè)觀鎖
strategy.setVersionFieldName("version");
strategy.setRestControllerStyle(true);
strategy.setControllerMappingHyphenStyle(true); //localhost:8080/hello_id_2
mpg.setStrategy(strategy);
mpg.execute(); //執(zhí)行
}
}