一、QueryWrapper是什么?

QueryWrapper就是在使用Mybatis-plus中真实用到的一种技术,也叫作构造器,能简化sql的操作。

二、常用方法总结

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);

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐