文章目录
开启MP运行日志
后台测试可以开启日志
上线运行时不要开启日志,因为服务器负担太大,容易崩溃
编辑yml
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
运行测试(getAll)
运行测试(getAll)2
小结
测试查询
分页查询
编写测试
@Test
void testGetPage(){
//两个参数分别代表“第几页”,每页显示多少条数据
Page page = new Page(2,2);
userMapper.selectPage(page,null);
}
出现问题
SELECT id,username,password,gender,addr FROM tb_user
并不是预期sql语句
编写MPConfig类
拦截器
package com.taotao.config;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* create by 刘鸿涛
* 2022/5/3 19:53
*/
@SuppressWarnings({"all"})
//配置类
@Configuration
public class MPConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}
}
测试通过
查看查询返回值
小结
条件查询
编写测试
@Test
void testGetBy(){
QueryWrapper<User> qw = new QueryWrapper();
qw.like("username","刘鸿涛");
userMapper.selectList(qw);
}
测试成功
语句优化(推荐使用)
语法集检查
编写测试
@Test
void testGetBy(){
QueryWrapper<User> qw = new QueryWrapper();
qw.like("username","刘鸿涛");
userMapper.selectList(qw);
}
测试成功
遇到问题
当姓名接收为null时,MP检测为%null%,语句,并不是理想结果
优化方案
@Test
void testGetBy2(){
String name = null;
LambdaQueryWrapper<User> qw = new LambdaQueryWrapper();
// if(name != null) qw.like(User::getUsername,name);
qw.like(name != null,User::getUsername,name); //如果为true就连,如果为false,就不连
userMapper.selectList(qw);
}
测试运行
相当于select * from tb_user