Mybatis-Plus 合并两个QueryWrapper对象的where条件

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.springboot.bean.Student;
import com.springboot.mapper.StudentMapper;
import com.springboot.service.StudentService;



    /**
     * 多个wrapper对象的条件合并在一个quer里面
     *
     * @param withOr   多个条件的关联是否为or联系
     * @param source   组合where条件之后的对象
     * @param wrappers 要组合的多个queryWrapper对象
     * @param <T>      泛型对象
     */
    static <T> void joinWhereSegment(boolean withOr, QueryWrapper<T> source, QueryWrapper<T>... wrappers) {

        for (QueryWrapper<T> wrapper : wrappers) { //注意,这里的or只是为了多一个括号,不是or操作
            if (wrapper == null || wrapper.getExpression().getNormal() == null || wrapper.getExpression().getNormal().isEmpty())
                continue;
            if (withOr) {
                source.or().nested(mq -> mq.or().getExpression().getNormal().addAll(wrapper.getExpression().getNormal()));
            } else {
                source.nested(mq -> mq.or().getExpression().getNormal().addAll(wrapper.getExpression().getNormal()));
            }
        }
    }

    static <T> QueryWrapper<T> joinGroupBySegment(QueryWrapper<T> source, QueryWrapper<T>... wrappers) {
        for (QueryWrapper<T> wrapper : wrappers) {
            if (wrapper == null || wrapper.getExpression().getGroupBy() == null || wrapper.getExpression().getGroupBy().isEmpty())
                continue;
            source.groupBy(wrapper.getExpression().getGroupBy().getSqlSegment().replaceAll("GROUP BY ","")) ;
        }
        return source;
    }

    public static void main(String[] args) {
        QueryWrapper<Student> queryWrapper = new QueryWrapper<Student>();
        queryWrapper.eq("sno", "123");
        queryWrapper.eq("name", "xiaoMing");
        queryWrapper.groupBy("name");

        QueryWrapper<Student> source = new QueryWrapper<>();
        source.eq("sno", "1234");
        source.groupBy("name");
        joinWhereSegment(true, source, queryWrapper);
        joinGroupBySegment(source, queryWrapper);
        System.out.println(source.getSqlSegment());
    }

结果:

(sno = #{ew.paramNameValuePairs.MPGENVAL1} OR (sno = #{ew.paramNameValuePairs.MPGENVAL1} AND name = #{ew.paramNameValuePairs.MPGENVAL2})) GROUP BY name, name

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值