MyBatis-Plus——使用查询构造器Wrapper & 简单分页操作

简介: MyBatis-Plus——使用查询构造器Wrapper & 简单分页操作

1.查询构造器:Wrapper


QueryWrapper(LambdaQueryWrapper)UpdateWrapper(LambdaUpdateWrapper) 的父类用于生成 sql where 条件, entity 属性也用于生成 sql where
件。 MP3.x开始支持lambda表达式,LambdaQueryWrapperLambdaUpdateWrapper支持 lambda 表达式的构造查询条件。


我们这里主要使用的是QueryWrapper这个类,它的父类AbstractWrapper实现了一个接口Compare<This, R>,在这个接口中,有大量用来拼接where子句中相关条件的方法。

1.    allEq:基于map的相等

2.    eq 等于 =

3.    ne 不等于 <>

4.    gt 大于 >

5.    ge 大于等于 >=

6.    lt 小于 <

7.    le 小于等于 <=

8.    between BETWEEN 1 AND 2

9.    notBetween NOT BETWEEN 1 AND 2

10.like LIKE '%%'

11.notLike NOT LIKE '%%'

12.likeLeft LIKE '%'

13.likeRight LIKE '%'

14.isNull 字段 IS NULL

15.isNotNull 字段 IS NOT NULL

16.in 字段 IN (value1, value2, ...)

17.notIn 字段 NOT IN (value1, value2, ...)

18.inSql 字段 IN ( sql 语句 )
: inSql("age", "1,2,3")--->age in (1,2,3,4,5,6)
: inSql("id", "select id from table where id < 3")--->id
in (select id from table where id < 3)

19.notInSql 字段 NOT IN ( sql 语句 )

20.groupBy GROUP BY 字段

21.orderByAsc 升序 ORDER BY 字段, ... ASC

22.orderByDesc 降序 ORDER BY 字段, ... DESC

23.orderBy 自定义字段排序 orderBy(true, true, "id", "name")--->order by id ASC,name ASC

24.having 条件分组

25.or OR 语句,拼接 + OR 字段=

26.and AND 语句,拼接 + AND 字段=

27.apply 拼接 sql

28.last sql 语句后拼接自定义条件

29.exists 拼接 EXISTS ( sql 语句 )
: exists("select id from table where age =
1")--->exists (select id from table where age = 1)

30.notExists 拼接 NOT EXISTS ( sql 语句 )

31.nested 正常嵌套不带 AND 或者 OR

2.案例详解


这篇文章中所用到的数据库表、实体类,mapper接口均和上一篇文章(链接:https://blog.csdn.net/weixin_43823808/article/details/118412431)相同,所以这里不再给出代码了,只是这篇文章中,不再使用xml映射文件了。

我将使用Wrapper这个查询构造器来实现查询操作。


2.1 测试方法

    @Test
    public void testAllEq() {
        QueryWrapper<Student> qw=new QueryWrapper<>();
        //将查询条件封装到Map集合中,and
        Map<String,Object> map=new HashMap<>();
        map.put("name","张三");
        map.put("age",22);
        qw.allEq(map);
        List<Student> students=mapper.selectList(qw);
        students.forEach( student -> System.out.println(student));
    }

    @Test
    public void testAllEq2() {
        QueryWrapper<Student> qw=new QueryWrapper<>();
        //将查询条件封装到Map集合中
        Map<String,Object> map=new HashMap<>();
        map.put("name","张三");
        map.put("age",null);
        /**
         * 第二个参数为 true:处理null值,where条件中加入 字段 IS NULL
         *         为 false:直接忽略null值,不添加到where子句中
         */
        qw.allEq(map,true);
        List<Student> students=mapper.selectList(qw);
        students.forEach( student -> System.out.println(student));
    }

qw.allEq(map,true)的执行结果


qw.allEq(map,false)的执行结果 


    @Test
    public void testEq() {
        QueryWrapper<Student> qw=new QueryWrapper<>();
        //eq等于
        qw.eq("name","李四");
        List<Student> students=mapper.selectList(qw);
        students.forEach( student -> System.out.println(student));
    }


    @Test
    public void testNe() {
        QueryWrapper<Student> qw=new QueryWrapper<>();
        //ne不等于
        qw.ne("name","李四");
        List<Student> students=mapper.selectList(qw);
        students.forEach( student -> System.out.println(student));
    }

    @Test
    public void testGt() {
        QueryWrapper<Student> qw=new QueryWrapper<>();
        //gt大于,ge大于等于
        //lt小于,le小于等于
        qw.gt("age",25);
        List<Student> students=mapper.selectList(qw);
        students.forEach( student -> System.out.println(student));
    }

    @Test
    public void testBetween() {
        QueryWrapper<Student> qw=new QueryWrapper<>();
        //between在两个值的范围之间(闭区间)
        //notBetween不在两个值范围之间(对应上面集合的补集)
        qw.between("age",30,36);
        List<Student> students=mapper.selectList(qw);
        students.forEach( student -> System.out.println(student));
    }

    @Test
    public void testLike() {
        QueryWrapper<Student> qw=new QueryWrapper<>();
        //like 匹配值 "%值%"
        //notLike 不匹配 "%值%"
        qw.like("name","周");
        List<Student> students=mapper.selectList(qw);
        students.forEach( student -> System.out.println(student));
    }

    @Test
    public void testLikeLeft() {
        QueryWrapper<Student> qw=new QueryWrapper<>();
        //likeLeft 匹配 like "%值"
        //likeRight 匹配 like "值%"
        qw.likeLeft("name","三");
        List<Student> students=mapper.selectList(qw);
        students.forEach( student -> System.out.println(student));
    }

    @Test
    public void testIsNull() {
        QueryWrapper<Student> qw=new QueryWrapper<>();
        //isNull 判断字段值为 null
        //isNotNull 字段值不为 null
        qw.isNull("age");
        List<Student> students=mapper.selectList(qw);
        students.forEach( student -> System.out.println(student));
    }

    @Test
    public void testIn() {
        QueryWrapper<Student> qw=new QueryWrapper<>();
        //in 在这个值列表中,在列表中的都是符合条件的。
        //notIn 不在列表中的
//        List<String> list=new ArrayList<>();
//        list.add("张三");
//        list.add("李四");
//        qw.in("name",list);
        //下面这行等价于上面注释掉的四行
        qw.in("name","张三","李四");
        List<Student> students=mapper.selectList(qw);
        students.forEach( student -> System.out.println(student));
    }

    @Test
    public void testInSql() {
        QueryWrapper<Student> qw=new QueryWrapper<>();
        //inSql 常用来做子查询 类似 in()
        //notInSql 类似 notIn()
        qw.inSql("age","select age from student where id=2");
        List<Student> students=mapper.selectList(qw);
        students.forEach( student -> System.out.println(student));
    }

    @Test
    public void testGroupBy() {
        QueryWrapper<Student> qw=new QueryWrapper<>();
        qw.select("status,count(*)");
        //groupBy 基于多个字段分组
        qw.groupBy("status");
        List<Student> students=mapper.selectList(qw);
        students.forEach( student -> System.out.println(student));
    }

    @Test
    public void testOrderByAsc() {
        QueryWrapper<Student> qw=new QueryWrapper<>();
        //orderByAsc 按字段升序
        //orderByDesc 按字段降序
        //orderBy 每个字段指定排序方向
        qw.orderByAsc("age");
        List<Student> students=mapper.selectList(qw);
        students.forEach( student -> System.out.println(student));
    }

    @Test
    public void testOr() {
        QueryWrapper<Student> qw=new QueryWrapper<>();
        //or 连接条件用 or,默认是 and
        //and 连接条件用 and
        qw.eq("name","张三").or().eq("age",24);
        List<Student> students=mapper.selectList(qw);
        students.forEach( student -> System.out.println(student));
    }

    @Test
    public void testLast() {
        QueryWrapper<Student> qw=new QueryWrapper<>();
        //last 拼接 sql 语句
        qw.eq("name","张三").or().eq("age",24).last("limit 1");
        List<Student> students=mapper.selectList(qw);
        students.forEach( student -> System.out.println(student));
    }

    @Test
    public void testExists() {
        QueryWrapper<Student> qw=new QueryWrapper<>();
        //exists 拼接 exists ( sql 语句 )
        //notExists 是 exists 的相反操作
        qw.exists("select id,name from student where age>36");
        List<Student> students=mapper.selectList(qw);
        students.forEach( student -> System.out.println(student));
    }


1.2 分页操作

首先添加分页插件,在原先的SSM中,我们需要在xml文件中使用<bean>标签进行声明配置;现在升级为了SpringBoot,就告别xml了,我们直接定义一个config包,在其中创建一个类,使用@Configuration注解标记该类为配置类,在其中使用@Bean注解就可以了。

package com.szh.mybatisplus.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
 *
 */
@Configuration
public class MyConfig {
    //分页插件
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}

下面是测试方法。

    @Test
    public void testPage() {
        QueryWrapper<Student> qw=new QueryWrapper<>();
        qw.gt("age",20);
        qw.orderByAsc("id");
        //设置分页的数据
        IPage<Student> page=new Page<>();
        page.setCurrent(1);//第1页
        page.setSize(3);//每页3条记录
        IPage<Student> result = mapper.selectPage(page, qw);
        List<Student> students = result.getRecords();
        System.out.println("总页数:" + result.getPages());
        System.out.println("总记录数:" + result.getTotal());
        System.out.println("当前页码:" + result.getCurrent());
        System.out.println("每页大小:" + result.getSize());
        students.forEach( student -> System.out.println(student));
    }

相关文章
|
3月前
|
SQL Java 数据库连接
MyBatis分页
MyBatis作为Java持久层框架,需结合数据库特性或插件实现分页。分页分为物理分页(如MySQL的LIMIT)和逻辑分页(内存截取),推荐使用PageHelper插件自动注入分页语句,提升开发效率与性能。需注意索引优化、深分页问题及多表关联时的兼容性,结合业务场景选择合适方案。
168 4
|
9月前
|
SQL Java 数据库连接
微服务——MyBatis分页
本文介绍了分页的多种实现方式,包括自带RowBounds分页、第三方插件PageHelper分页、SQL分页、数组分页及拦截器分页。其中,RowBounds是先查询全部结果再内存分页;PageHelper通过修改SQL动态添加分页关键字;SQL分页依赖数据库自身的分页功能如`LIMIT`;数组分页则是查询全量数据后用`subList`方法截取;拦截器分页则统一在SQL后添加分页语句。最后总结逻辑分页适合小数据量,但大数据量易内存溢出;物理分页虽小数据量效率较低,但更适合大数据场景,优先推荐使用。
136 0
|
9月前
|
SQL Oracle 关系型数据库
【YashanDB知识库】Mybatis-Plus调用YashanDB怎么设置分页
【YashanDB知识库】Mybatis-Plus调用YashanDB怎么设置分页
|
5月前
|
SQL XML Java
MyBatis Mapper中使用limit参数的查询问题
总结而言,MyBatis中使用 `limit`参数的查询可以高度定制并且灵活,基于方法签名和XML映射文件的组合来达成多样化的查询需求。通过参数化查询和动态SQL,MyBatis可以有效地处理各种复杂情境下的数据库操作,并且将SQL语句的维护与业务代码的编写相分离,提升代码的可维护性和可阅读性。
531 13
|
7月前
|
SQL Java 数据安全/隐私保护
发现问题:Mybatis-plus的分页总数为0,分页功能失效,以及多租户插件的使用。
总的来说,使用 Mybatis-plus 确实可以极大地方便我们的开发,但也需要我们理解其工作原理,掌握如何合适地使用各种插件。分页插件和多租户插件是其中典型,它们的运用可以让我们的代码更为简洁、高效,理解和掌握好它们的用法对我们的开发过程有着极其重要的意义。
757 15
|
6月前
|
SQL Java 数据库
解决Java Spring Boot应用中MyBatis-Plus查询问题的策略。
保持技能更新是侦探的重要素质。定期回顾最佳实践和新技术。比如,定期查看MyBatis-Plus的更新和社区的最佳做法,这样才能不断提升查询效率和性能。
293 1
|
10月前
|
监控 安全 数据库
【YashanDB 知识库】Mybatis-Plus 调用 YashanDB 怎么设置分页
数据库状态分为正常与异常两种情况。当出现异常时,首先查看告警列表确认问题(如实例无法连接),并尝试用数据库用户名和密码登录。若能登录,说明主实例故障已切换至备库;若无法登录或为单节点,则需进一步排查。接着检查监控项,若有数据表明主实例故障,无数据则可能是通信中断。随后检查主机上的服务是否存在,若存在但通信受限,需排查安全设置或网络;若服务不存在,可能因重启或断电导致,需手动启动相关服务。最终在YashanDB列表中确认状态恢复。
|
9月前
|
SQL Java 关系型数据库
MyBatis篇-分页
本文介绍了多种分页方式,包括自带rowbound内存分页、第三方插件pagehelper(通过修改SQL实现分页)、SQL分页(依赖limit或rownum等关键字)、数组分页(先查询全部数据再用subList分页)、拦截器分页(自定义拦截器为SQL添加分页语句)。最后总结了逻辑分页(内存分页,适合小数据量)和物理分页(直接在数据库层面分页,适合大数据量)的优缺点,强调物理分页优先于逻辑分页。
|
9月前
|
SQL Java 数据库连接
MyBatis 实现分页的机制
MyBatis 的分页机制主要依赖于 `RowBounds` 对象和分页插件。`RowBounds` 实现内存分页,适合小数据量场景,通过设定偏移量和限制条数对结果集进行筛选。而针对大数据量,则推荐使用分页插件(如 PageHelper),实现物理分页。插件通过拦截 SQL 执行,动态修改语句添加分页逻辑,支持多种数据库方言。配置插件后,无需手动调整查询方法即可完成分页操作,提升性能与灵活性。
229 0
|
9月前
|
Oracle 关系型数据库 Java