mybatis-plus自定义注解自动生成QueryWrapper

  |   3 评论   |   597 浏览

问题描述

在用mybatis-plus写查询接口时,经常会写出类似下面的代码

1LambdaQueryWrapper<Student> queryWrapper = Wrappers.lambdaQuery(Student.class)
2    .like(StringUtils.isNotBlank(student.getName()), Student::getName, student.getName())
3    .eq(student.getSex() != null, Student::getSex, student.getSex())
4    .ge(student.getAge() != null, Student::getAge, student.getAge());

mp自带的@TableField(condition=SqlCondition.XX)并不能很好的控制要查询的字段,并且只支持eq、noteq、like、likeleft和likeright(v3.4.3)
在字段比较多的情况下会很繁琐,我解决的办法是封装自定义注解来拼装QueryWrapper,源码我放在gitee上,为了方便使用还将jar上传了中央仓库,代码很简单,一个注解类,一个拼装工具类mybatis-plus-wrapper: 简化QueryWrapper的注解实现 (gitee.com)

使用说明

1. 在pom.xml中引入jar包

1<dependency>
2    <groupId>com.gitee.wenbo0</groupId>
3    <artifactId>mybatis-plus-wrapper</artifactId>
4    <version>0.1</version>
5</dependency>

2. 在实体类或DTO中需要查询的字段上增加注解@Wrapper

 1@Getter
 2@Setter
 3@Accessors(chain = true)
 4public class Student {
 5    private String id;
 6    @Wrapper(WrapperType.LIKE)
 7    private String name;
 8    @Wrapper
 9    private Integer sex;
10    @Wrapper(WrapperType.GE)
11    private Integer age;
12}

在构建QueryWrapper的时候使用

1QueryWrapper<Student> queryWrapper = WrapperUtil.buildQueryWrapper(student);

这时WrapperUtil构建的QueryWrapper等价于简介中的代码构建的QueryWrapper。

3. @Wrapper注解介绍

注解有四个属性 分别是

 1/**
 2 * 条件类型
 3 */
 4WrapperType value() default WrapperType.EQ;
 5
 6/**
 7 * 数据库字段名 默认为pojo字段名小驼峰转下划线
 8 */
 9String columnName() default "";
10
11/**
12 * 是否忽略空白字符串
13 */
14boolean ignoreBlank() default true;
15
16/**
17 * 是否忽略null
18 */
19boolean ignoreNull() default true;

3.1 value可选值为EQ, LIKE, LIKE_LEFT, LIKE_RIGHT, LT, GT, LE, GE, IN, NOT_IN,分别调用mybatis-plus中的同名方法,默认值为EQ

目前IN和NOT_IN只支持数组和字符串类型, 字符串类型默认逗号分割字符串

3.2 ignoreNull设置为false时将会把null作为条件查询

3.3 ignoreBlank设置为false时,并且字段为String类型,将会把空字符串作为条件查询


作者:wenbo

评论

  • 淄博漏水检测 回复»

    不错,必须赞一个!

  • 李海博客 回复»

    您好,朋友:
    见字如面,
    I’M 李海博客,是最老的一批九零后。
    我通过 [虫洞] 页面随机穿越而来。
    [虫洞] 页面和 [十年之约] 项目是我忒喜欢的项目。
    即便我目前还暂时没被收录,但这不重要。
    我喜欢这种随机、未知和不经意的相遇。
    因此我每到访一处,也总会随机留下点啥。
    类似于 [I’M 李海博客,到此一游] 等等废话;
    或 [您的博客真个性 / 漂亮 / 有 biger] 等等彩虹屁。
    您的博客是我被传送到访的未知地之一;
    祝您诸事顺遂,万事安康。
    期待和您再次相遇。
    毕竟,苍生众相,有趣的灵魂,可不多…
    ——I’M 李海博客。
    https://www.lihaiblog.cn =

  • 鸟叔 回复»

    学习了,感谢分享

发表评论


取消