mybatisPlus-wrapper条件构造器
1 在测试包下编写一个新测试类WrapperTest.java
src/test/java/com/lv/mybatis_plus/WrapperTest.java
package com.lv.mybatis_plus;
import com.lv.mybatis_plus.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class WrapperTest {
@Autowired
private UserMapper userMapper;
}
2 多条件查询
src/test/java/com/lv/mybatis_plus/WrapperTest.java
@Test
void test1() {
//查询name不为空,邮箱不为空的,并且年龄大于等于12的用户
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper
.isNotNull("name")
.isNotNull("email")
.ge("age",12);
userMapper.selectList(wrapper).forEach(System.out::println); //和我们刚才学习的map对比一下
}
运行测试查看控制台生成的sql
3 条件查询
src/test/java/com/lv/mybatis_plus/WrapperTest.java
@Test
void test2(){
//查询名字是可乐
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name","Tom");
User user = userMapper.selectOne(wrapper); //查询一个数据,出现多个结果使用List 或者 Map
System.out.println(user);
}
运行,查看控制台生成的sql
4 区间条件查询
src/test/java/com/lv/mybatis_plus/WrapperTest.java
@Test
void test3(){
//查询年龄在 22 ~ 25 岁 之间的用户
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.between("age",20,25); //区间
Integer count = userMapper.selectCount(wrapper);//查询结果数
System.out.println(count);
}
运行,查看控制台生成的sql
5 模糊查询
src/test/java/com/lv/mybatis_plus/WrapperTest.java
@Test
void test4(){
//名字里面不包含a的用户
QueryWrapper<User> wrapper = new QueryWrapper<>();
// likeRight右边加%,likeLeft左边加%
wrapper
.notLike("name","a")
.likeRight("email","t");
List<Map<String, Object>> maps = userMapper.selectMaps(wrapper);
maps.forEach(System.out::println);
}
运行,查看控制台生成的sql
6 拼接子查询sql
src/test/java/com/lv/mybatis_plus/WrapperTest.java
@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);
}
运行,查看控制台生成的sql
7 排序查询
src/test/java/com/lv/mybatis_plus/WrapperTest.java
@Test
void test6(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
//通过id进行降序排序
wrapper.orderByDesc("id");
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}
运行,查看控制台生成的sql
其它的查询方式可以参照官方文档: 条件构造器 | MyBatis-Plus (baomidou.com)