Mybatis-动态SQL-查询与更新

查询经常使用到<if><choose><when><otherwise><trim>标签,他们都支持ognl表达式
--|<if> 条件判断和Java中if同样,如sql

<if test="id!=null and id!=''">

--|<choose>就像Java的带有break的switch,搭配<when><otherwise>使用
----|<when>当条件知足是执行拼接其中的内容,如ide

<when test="custId!=null and custId%2==0" >
				concat(cust_name,'_aa') cust_name
			</when>

----|<otherwise>当全部<when>都不知足,则拼接它的内容,如code

<otherwise>
				concat(cust_name,'_bb') cust_name
			</otherwise>

一个完整的查询例子配置:xml

<!-- 复杂查询,使用if choose 标签 -->
	<select id="getCustsByCust" resultType="com.jv.dynamic.bean.Cust">
		select cust_id,
		<choose>
			<when test="custId!=null and custId%2==0" >
				concat(cust_name,'_aa') cust_name
			</when>
			<otherwise>
				concat(cust_name,'_bb') cust_name
			</otherwise>
		</choose>
		from cust
		<where>
			<!-- ognl表达式还支持&&等操做符,可是在xml中须要使用其转义字符
				好比:<if test="custId!=null!=null &amp;&amp; custId!=null!=&quot;&quot;">
				其中&amp;是表明&符号;&quot;表明双引号
				
				为了阅读方便,推荐使用肺转移符
			-->
			<if test="custId!=null and custId!=''">
				cust_id=#{custId}
			</if>
			<if test="custName!=null and custName!=''">
				and cust_name like #{custName}
			</if>
		</where>
	</select>

在实际项目开发中,有的公司或者开发人员喜欢不使用<where>标签,而是直接写"where 1=1",后面全部的条件判断对应的SQL都是"and"开头,这种写法也讨巧,思路灵活。开发

而为何使用<where>标签喃,由于Mybatis能够帮助咱们若是把“and”写在开头的状况下,不出现拼接完成sql出现where and column_name = ?的状况。若是把“and”写在最后,<where>标签也就没有用了,不过能够使用<trim>标签,好比:get

<trim suffixOverrides="">
            <if test="custId!=null and custId!=''">
				cust_id=#{custId} and
			</if>
			<if test="custName!=null and custName!=''">
				cust_name like #{custName}
			</if>
         </trim>


更新经常使用到<set>标签it

<update id="updateAuthorIfNecessary">
  update Author
    <set>
      <if test="username != null">username=#{username},</if>
      <if test="password != null">password=#{password},</if>
      <if test="email != null">email=#{email},</if>
      <if test="bio != null">bio=#{bio}</if>
    </set>
  where id=#{id}
</update>
相关文章
相关标签/搜索