Java中QueryWrapper的使用
Java中QueryWrapper的使用
前言
提示:在实际开发中,我们现在越来越要熟悉的使用Mybatis-plus等便捷式开发技术了。小编不才,接下来我将会将我开发中常用到的方法总结一下。
提示:以下是本篇文章正文内容,下面案例可供参考
一、QueryWrapper是什么?
说明:其实,说白了,QueryWrapper就是咱们在使用Mybatis-plus中真实用到的一种技术,也叫作构造器。
二、常用使用方法总结
1.单表查询
代码如下(示例):我要查询姓名、班级、年龄符合前端传过来参数的数据并进行排序。
@GetMapping("/list")
public TableDataInfo list(Student student){
LambdaQueryWrapper<Student> lqw = new LambdaQueryWrapper<Student>();
lqw.eq(Student::getName, student.getName());
lqw.like(Student::getClass,student.getClass());
lqw.between("age",student.getAge1(),student.getAge2());
lqw.orderByAsc("age");
List<Student> list = studentService.list(lqw);
}
以上代码对应的sql为:
select * from student where name = ? and class like %?% and age between ? and ? order by ? asc
由此可以看出,QueryWrapper其实可以理解成一个放查询条件的盒子,我们把查询条件放在里面,他就会自动按照对应的条件进行查询数据。
根据不同的查询要求,有不同的用法,常用到的比如:eq、like、and、or、isNull、isNotNull、ne、likeRight、between等;使用方法及说明见下图。
2.多表联合查询
代码如下(示例):
//Controller
@GetMapping("/listAndClass")
public TableDataInfo listAndClass(Student student)
{
QueryWrapper<Student > qw = new QueryWrapper<Student >();
if(StringUtils.isNotBlank(student.getName())){
qw.eq("s.name",student.getName());
}
if(StringUtils.isNotBlank(student.getClassName())){
qw.like("c.name",student.getClassName());
}
startPage();
List<Student > list = studentService.listAndClass(qw);
return getDataTable(list);
}
//Service
List<Student> listAndClass(QueryWrapper<Student> qw);
//Service impl
@Override
public List<Student> listAndClass(QueryWrapper<Student> qw) {
return this.getBaseMapper().listAndClass(qw);
}
//Mapper
@Select("select s.*,c.name from student s left join class c on s.id = c.student_id "+
"${ew.customSqlSegment}")
List<YwSpaqjgDj> listAndClass(@Param(Constants.WRAPPER) QueryWrapper<Student> qw);
