MyBatis的Example的and 和or的复合查询(转)
原文链接:http://blog.csdn.net/hanchao_h/article/details/54848605
今天项目中有一个SQL的查询语句大概如下方式:
select * from table where xxx = "xxx" and (xx1="xx1" or xx2="xx2")
如果实用Mybatis的Example是很难直接直接拼写成这样子的形式,只能通过拆分成等价的SQL再实用Example拼接
调整下的公式如下:select * from table where (xxx = "xxx" and xx1="xx1") or (xxx = "xxx" and xx2="xx2")
然后实用的在java端的代码如下
- CollectDriverExample example=new CollectDriverExample();
- example.or().orCarNumLike("%"+searchParam+"%").andUserIdEqualTo(userId);
- example.or().orDriverNameLike("%"+searchParam+"%").andUserIdEqualTo(userId);
因为mybatis的Example文件对于这方面的支持也是有限的,所以一些复杂的语句我觉得还是手写比较好,毕竟可读性要好点。
首先:
我们观察Example类的结构,发现它是没有or开头的方法的,只找到下面一个方法:
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
然后,我们分析在xml中时怎么对Criteria进行处理,拼接sql的:
<sql id="Example_Where_Clause" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
-->
<where >
<foreach collection="oredCriteria" item="criteria" separator="or" >
<if test="criteria.valid" >
<trim prefix="(" suffix=")" prefixOverrides="and" >
<foreach collection="criteria.criteria" item="criterion" >
<choose >
<when test="criterion.noValue" >
and ${criterion.condition}
</when>
可以看到,对于多个criteria,使用的是or进行拼接的,对于criteria内部的condition使用的是and连接,并且多个criteria使用().
也就是说我们只能拼接成where (a and b ) or (c and d)的形式,所以多付复合条件带or的话,自定义sql或者拆分条件组成两个条件。

浙公网安备 33010602011771号