MyBatis-Plus条件构造器和常用接口
一、wapper介绍
Wrapper : 条件构造抽象类,最顶端父类
AbstractWrapper : 用于查询条件封装,生成 sql 的 where 条件
QueryWrapper : 查询条件封装
UpdateWrapper : Update 条件封装
AbstractLambdaWrapper : 使用Lambda 语法
LambdaQueryWrapper :用于Lambda语法使用的查询Wrapper
LambdaUpdateWrapper : Lambda 更新封装Wrapper
1.写一个测试类
@SpringBootTest
public class QueryWrapperTests {
//自动注入UserMapper类
@Autowired
private UserMapper userMapper;
}
2.测试ge、gt、le、lt、isNull、isNotNull
@Test
public void testQuery() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//使用QueryWrapper进行sql语句的条件拼接
queryWrapper
.isNull("name")
.ge("age", 12)
.isNotNull("email");
//返回执行影响的数量
int result = userMapper.delete(queryWrapper);
System.out.println("delete return count = " + result);
}
3.测试eq、ne
@Test
public void testSelectOne() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("name", "Tom");//匹配一个条件
//注意:seletOne()返回的是一条实体记录
User user = userMapper.selectOne(queryWrapper);//只能返回一条记录,多于一条则抛出异常
System.out.println(user);
}
4.测试between、notBetween
@Test
public void testSelectCount() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.between("age", 20, 30);//包含大小边界
Integer count = userMapper.selectCount(queryWrapper); //返回数据数量
System.out.println(count);
}
5.测试like、notLike、likeLeft、likeRight
@Test
public void testSelectMaps() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper
.select("name", "age")
.like("name", "e")
.likeRight("email", "5");
List<Map<String, Object>> maps = userMapper.selectMaps(queryWrapper);//返回值是Map列表
maps.forEach(System.out::println);
}
6.测试orderBy、orderByDesc、orderByAsc
@Test
public void testSelectListOrderBy() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.orderByDesc("age", "id");
List<User> users = userMapper.selectList(queryWrapper);
//返回排序好的list集合
users.forEach(System.out::println);
}
二、查询方式表