一. 前言
在很多的业务场景中,除了简单的增删查改语句,我们还会有用到一些特殊的查询,比如说条件查询,模糊查询等等,在java中构建条件语句的封装类也有很多,其底层就是帮我们把sql语句给封装好,方便我们进行调用.这里我浅显的记录两种构造条件语句的类,
-
第一种:QueryWrapper
举个例子:查询课程信息,带分页显示
它的使用方式如下:
//创建一个page对象
Page<EduCourse> pageCourse = new Page<>(current,limit);
//构建条件
QueryWrapper<EduCourse> courseWrapper = new QueryWrapper<>();
//多条件组合查询
String title = courseQuery.getTitle();
String status = courseQuery.getStatus();
//判断条件值是够为空,如果不为空,拼接条件
if (!StringUtils.isEmpty(title)){
courseWrapper.like("title",title);
}
if (!StringUtils.isEmpty(status)){
courseWrapper.eq("status",status);
}
courseService.page(pageCourse,courseWrapper);
long total = pageCourse.getTotal();//总记录数
List<EduCourse> records = pageCourse.getRecords();
return R.ok().data("total",total).data("rows",records);
}
代码解释:
首先我们用了一个Page对象用来分页,这个暂且不管,下面的QueryWrapper才是重点,通过实例化一个QueryWrapper对象,然后通过其方法like,或者eq进行模糊查询和等值查询,这里一般会使用StringUtils工具类进行一个值的判断
关于QueryWrapper的用法还有很多,如下图:
- 第二种:通过new一个Example对象进行方法的实现,从而达到模糊查询的目的.首先要注意的是这个Example对象是tk包下的
导入其他的包会导致方法使用不了,我们来看看具体的使用案例
@Override
public List<Brand> findList(Brand brand) {
//自定义条件搜索对象
Example example = new Example(Brand.class);
//条件构造器
Example.Criteria criteria = example.createCriteria();
//brand.name != null or brand.letter != null
if (!StringUtils.isEmpty(brand.getName())){
/**
* 1.Brand的属性名
* 2.占位参数,搜索的条件
*/
criteria.andLike("name","%"+brand.getName()+"%");
}
if (!StringUtils.isEmpty(brand.getLetter())){
criteria.andEqualTo("letter",brand.getLetter());
}
List<Brand> brandList = brandMapper.selectByExample(example);
return brandList;
}
在这里我们通过name,和Letter进行一个简单的模糊查询,首先都需要进行条件构造,这里与QueryWrapper不一样,注意看
Example.Criteria criteria = example.createCriteria();
两者实现的功能是一样的.
来看看Example提供的方法:
条件带分页实现:
public Example createExample(Brand brand){
//自定义条件搜索对象
Example example = new Example(Brand.class);
//条件构造器
Example.Criteria criteria = example.createCriteria();
//brand.name != null or brand.letter != null
if (!StringUtils.isEmpty(brand.getName())){
/**
* 1.Brand的属性名
* 2.占位参数,搜索的条件
*/
criteria.andLike("name","%"+brand.getName()+"%");
}
if (!StringUtils.isEmpty(brand.getLetter())){
criteria.andEqualTo("letter",brand.getLetter());
}
return example;
}
@Override
public PageInfo<Brand> findPage(Brand brand,Integer page, Integer size) {
//分页
PageHelper.startPage(page,size);
//搜索数据 name,letter
Example example = createExample(brand);
List<Brand> brandList = brandMapper.selectByExample(example);
//封装
PageInfo<Brand> pageInfo = new PageInfo<>(brandList);
return pageInfo;
}
/**
* 分页查询实现
*/
@PostMapping("/search/{page}/{size}")
public Result<PageInfo<Brand>> findBrandAndPage(
@RequestBody Brand brand,
@PathVariable("page") Integer page,
@PathVariable("size") Integer size){
//调用
PageInfo<Brand> pageInfo = brandService.findPage(brand,page,size);
Result<PageInfo<Brand>> result = new Result<>(true, StatusCode.OK, "条件带分页查询成功", pageInfo);
return result;
}