首先说明一下,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,就大概使用以下几个方法做了实验
- 是用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的方式试一把。
- 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。因此我写这个给想偷懒的小伙伴一个方向哈。