Mybatis模糊查询和动态sql语句的用法


当前第2页 返回上一页

choose , when 和 otherwise 标签

<select id="select01" resultMap="BasicResultMap">
   SELECT 
   * 
   FROM
   oa_employee 
   <where>
   <choose>
    <when test="emp_name != null and emp_name != ''">
       and emp_name = #{emp_name }
    </when>
     <when test="emp_sex != null and emp_sex != ''">
       and sex = #{emp_sex}
    </when>
    <otherwise>
      emp_id = 50
    </otherwise>
   </choose>
   </where>
  </select>

当所有条件不满足时,执行otherwise标签的内容。

trim标签

<select id="select01" resultMap="BasicResultMap">
   SELECT 
   * 
   FROM
   oa_employee 
    <trim prefix="where" prefixOverrides="and |or ">
    <if test="emp_name != null and emp_name != ''">
      and emp_name = #{emp_name }
    </if>
    <if test="emp_sex != null and emp_sex != ''">
       and sex = #{emp_sex}
    </if>
  </trim>

trim标签的属性及其含义

  • - prefix : 标签之间有内容在最前面加入
  • - prefixOverrides: 检查内容的最前面是否匹配,匹配就删除
  • - suffix: 标签之间有内容在最后面加入
  • - suffixOverrides:检查内容的最后面是否匹配,匹配就删除

set标签

set标签常用于update操作,并且会自动抹掉无关的,

 <update id="update01" >
  UPDATE 
   oa_employee 
  <set>
    <if test="emp_name != null and emp_name != ''">
       emp_name = #{emp_name}
    </if>
    <if test="emp_sex != null and emp_sex != ''">
      ,sex = #{emp_sex}
    </if>
  </set>
  WHERE emp_id = 50 
  </update>

foreach标签

foreach 用于处理数组或者list集合,下面是一个批量添加的例子

 <insert id="insert01">
  INSERT INTO 
  oa_employee 
  ( emp_name, sex, fk_dept_id) 
  VALUES
  <foreach collection="list" item="employee" separator=","> 
   (#{employee.emp_name},#{employee.emp_sex},#{employee.fk_dept_id})
  </foreach>
  </insert>

其中 如果参数为数组 则collection只能为“array” 参数为List集合则collection只能为 “list” item类似JSTL 中的var的作用, 指代容器中的每一个对象。separator=”,”的含义是每条数据以 , 分割。 未注明的属性有 open 和 close 他们的含义是在遍历开始和结束时分别添加其内容。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。如果你想了解更多相关内容请查看下面相关链接

更多SQL内容来自木庄网络博客


打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...