Java中QueryWrapper的使用

2年前 (2022) 程序员胖胖胖虎阿
298 0 0

Java中QueryWrapper的使用

文章目录

    • Java中QueryWrapper的使用
  • 前言
  • 一、QueryWrapper是什么?
  • 二、常用使用方法总结
    • 1.单表查询
    • 2.多表联合查询
  • 总结

前言

提示:在实际开发中,我们现在越来越要熟悉的使用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等;使用方法及说明见下图。

函数名 说明 例子
eq 等于 例:eq(“name”,“张子”) ===> name = ‘张子’
ne 不等于 例:ne(“name”,“张子”) ===> name <> ‘张子’
gt 大于 例:gt(“age”,“18”) ===> age>18
lt 小于 例:lt(“age”,“18”) ===> age<18
between 在值1到值2之间 例:between(“age”,18,30) ===> 18<age<30’
like 模糊查询 例:like(“name”,“张”) ===> name like ‘%张%’
isNull 字段为NULL 例:isNull(“name”) ===> name is null

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

总结

以上就是今天我所讲的内容。如果你喜欢我的文章,对你还算是有所收获的话,请点赞、评论、收藏,你对我的支持将是我最大的动力!Thank You!

版权声明:程序员胖胖胖虎阿 发表于 2022年9月26日 上午10:00。
转载请注明:Java中QueryWrapper的使用 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...