目录

MybatisPlus中的customSqlSegment动态拼接where条件

MybatisPlus中的customSqlSegment动态拼接where条件

前言

在对于一些MybatisPlus提供的Api无法实现的SQL场景,我们需要去到xml文件中写SQL语句,where条件的编写让人十分头疼,那么有没有一种便捷的方式通过MybatisPlus提供的Api快捷拼接where条件呢?有的有的,这就是今天要介绍的customSqlSegment。

编写流程

创建mapper接口

入参定义为QueryWrapper,用来接收查询条件。

https://i-blog.csdnimg.cn/direct/b0ff1885bdf346699650dd7530168157.png

调用mapper接口

https://i-blog.csdnimg.cn/direct/2de442112cca4e9f910f377ce91e8c85.png

构造QueryWrapper来设置查询条件,这里的test是自定义的方法用于判断条件是否成立,成立返回true,eq等条件方法才会拼接,相当于xml中的,test方法在下方需要可自取。

public static boolean test(Object o) {
        if (o == null) {
            return false;

        }
        if (o instanceof String s) {
            return !s.isBlank();
        }
        if (o instanceof List<?> list) {
            return !list.isEmpty();
        }
        return true;
    }

编写SQL

在xml中正常编写SQL,where条件部分通过 ${接口中参数别名.customSqlSegment} 来引用条件,MybatisPlus会自动为我们拼接上where条件。

https://i-blog.csdnimg.cn/direct/f67c5ceeea01411a8790db8ba8b55f44.png

这样一来,即使需要在xml中编写SQL语句,也不用进行繁琐的拼接条件工作了,代码更加简洁,可维护性也更高了。