tk.mybatis 复杂多条件 or and

首先说明一下,tk是用于不推荐example写复杂的sql,后期维护麻烦,特别是复杂的子嵌套。但是今天写一个小需求,其他接口的CRUD都比较简单用example轻松搞定。但是出现一个查询需要是要根据多个条件先and后or。大概如下:

select * from table where
( ( a = ? and b = ? ) 
    or ( a= ? and b = ? ) 
    or ( a= ? and b = ? ) ) 
and c=?

出于懒惰不想专门为了这个接口写个xml,就大概使用以下几个方法做了实验

  1. 是用example的
            Criteria criteria = example.createCriteria();
            for (String s : list) {
              criteria.andEqualTo("a",s.split("/")[0]);
              criteria.andEqualTo("b",s.split("/")[1]);
            }
            Criteria criteria1 = example.createCriteria();
            criteria.andEqualTo("c","");

    出现sql如下图:

    select * from table where
     (( a = ? and b = ? ) 
        or ( a= ? and b = ? ) 
        or ( a= ? and b = ? ) 
    and c=?)

    乍一看没问题,实际上是有问题的,注意看他的第一个括号,意思已经变了。所以这种写法是不支持,但是我写了这么久让我去写sql ,我心有不甘哈哈哈。于是跟同事讨论一下,想试试用condition的方式试一把。

  2. orCondition试试
             Criteria criteria = example.createCriteria();
            for (String s : list) {
              criteria.orCondition("( (a = '" + s.split("/")[0] + "' and b = '" + s.split("/")[1] + "') ");
            }
            Criteria criteria1 = example.createCriteria();
            criteria.andEqualTo("c","");

    结果就是:

    select * from table where
     (( a = ? and b = ? ) 
        or ( a= ? and b = ? ) 
        or ( a= ? and b = ? ) )
    and c=?)

    哈哈哈,实现我的需求,就这样子。在解决这个问题,我搜过很多资料都没相关解决方案,可能觉得这已经是复杂的sql。因此我写这个给想偷懒的小伙伴一个方向哈。

  3. 最后说一点,拼接条件要检验,防止SQL注入。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值