Mybatis中用OGNL表达式处理动态sql

常用的Mybatis动态sql标签有6种:

1. if 语句 (简单的条件判断)
2. choose (when,otherwize) ,相当于java 语言中的 switch ,与 jstl 中的choose 很类似.
3. trim (对包含的内容加上 prefix,或者 suffix 等,前缀,后缀)
4. where (主要是用来简化sql语句中where条件判断的,能智能的处理 and or ,不必担心多余导致语法错误)
5. set (主要用于更新时)
6. foreach (在实现 mybatis in 语句查询时特别有用)

(1) if

模糊查询

<select id="select1"  resultType="BaseresultMap">
  SELECT * FROM User WHERE Age = ‘18’ 
  <if test="name != null">
    AND name like #{name}
  </if>
</select>

年龄18且可以模糊搜索姓名

(2)choose,when,otherwize

当Job参数有传入时,就找出对应工作的人,否则就找出Job为none的人,而不是所有人

<select id="select2"  resultType="BaseresultMap">
  SELECT * FROM User WHERE Age = ‘18’ 

  <choose>
    <when test="Job != null">
      AND Job =#{Job}
    </when>
    <otherwise>
      AND Job="none"

    </otherwise>
  </choose>
</select> 


(3)foreach

  <select id="select5" resultType="BaseresultBase">
        select * from User where id in
        <foreach collection="list" index="index" item="item" open="(" separator="," close=")">
            #{item}
        </foreach>
    </select>

public List<User> select5(List<Integer> ids); 


(4) where set trim

where,set

为什么要用where,因为单纯的写where可能会导致 where And ... 和 where .....情况的发生,Set也是一样的

当然 trim 标签是万能的

<select id="select3"  resultType="BaseresultMap">
  SELECT * FROM User
<where>

  <if test="Age != null">
    Age = #{Age}
  </if>
  <if test="Job != null">
    AND Job like #{Job}
  </if>

<where>
</select>

<update id="update1">
  update User
    <set>
      <if test="username != null">username=#{username},</if>
      <if test="password != null">password=#{password},</if>
      <if test="Age != null">Age =#{Age}</if>
    </set>
  where id=#{id}
</update>












评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值