Mybatis动态SQL
Mybatis的强大特征之一就是动态SQL。Mybatis采用功能强大的基于OGNL表达式来淘汰其他大部分元素。使用mybatis提供的各种标签方法实现动态拼接sql。动态传参数,如果传入的这个参数,就判断进行SQL拼接,没有就不判断。
一、if,where 标签
进行简单的判断,利用if实现简单的条件选择,动态SQL通常要做的事情就是根据条件包含where子句的一部分。
注意:Mybatis动态sql单一基础类型参数使用if标签时,test中应该使用_parameter
<select id="findByAddress" parameterType="string" resultType="com.fyl.entity.User">
select * from user
<where>
<if test="_parameter!=null">
and address=#{address}
</if>
</where>
</select>
test属性 :If标签中test属性里面是判断条件,test属性值是一个符合OGNL要求的判断表达式,表达式的结果可以为true或false,除此之外所有非0值都为true
例:动态传入多个参数:
<select id="findByUsernamePassword" parameterType="Map" resultType="com.fyl.entity.User">
select * from user
<where>
<if test="username!=null">and username=#{username}</if>
<if test="password!=null">and password=#{password}</if>
</where>
</select>
注:test使用
不为空,且不为空字符串: <if test =”id!=null and id!=’’”>
注:if中test里的判断:如果是字符串判断:
错误: <if test =”id!=null and id!=’1’”>
正确写法是:<if test =“id!=null and id!=’1’.toString()”>
<if test = ‘id!=null and id!=“1” ’>
二、where标签
<where>的作用和where子句类似,不过使用where标签可以过滤掉多余的and 或or 关键字,防止出现语法错误。
注:Mybatis中的where标签和where子句的区别?
<where> JLMQSJCL>0 or JTSJCL>0
<if test="xzqh!=null and xzqh.length>0">
and Q.VILLAGEID LIKE CONCAT(#{xzqh},'%')
</if>
<if test="districts != null">
<foreach collection="districts" index="key" open=" AND (" separator=" OR " close=") " item="item">
SUBSTR(Q.VILLAGEID, 1, ${key}) IN ${item}
</foreach>
</if>
</where>
如果前一个if标签不成立,后一个if中有and,那么如果使用<where>标签会自动把and忽略,而是用where子句的话可能会出现sql语法错误,如果要使用where子句可以在前面写上:where 1=1 这样就不会报错了
三、choose标签
<choose> <when> <otherwise>用于多条件判断,相当于java中if…else if… else这种形式或者是switch case default
<choose><!-- 处理方法 -->
<when test="hobby.indexOf(',') == -1">
AND hobby= #{hobby}
</when>
<otherwise>
AND hobby in
<foreach item="item" index="index" collection="hobby.split(',')"
open="(" separator="," close=")">
'${item}'
</foreach>
</otherwise>
</choose>
若此sql里只有choose这个查询条件的话,可以将where放在 <when>和<otherwise>里,因为有一个<when>里条件成立,就不会走其他<when>或<otherwise>,如果在表后写where 如果<choose>里的条件都不成立,这个语句就会出错。
四、foreach标签
向sql传递数组或List,mybatis使用foreach解析,如下:
例:
<if test="fields !=null">
<foreach collection="fields" item="item" open=" AND(" separator="OR" close=")">
#{item} = 1
</foreach>
</if>
五、SQL片段
sql中可将重复的sql提取出来,使用时用include引用即可,最终达到sql重用的目的