mybatis动态sql使用

来源:互联网 发布:淘宝单主持怎样找商家 编辑:程序博客网 时间:2024/06/07 22:21

1.if(用于判断条件,如果成了则执行相关语句)

select id="dynamicIfTest" resultType="User">      select * from user where sex = 'male'      <if test="address != null">        and address = #{address}      </if></select>
2.choose(相当于java中的switch,一旦有条件满足就会跳出)

<select id="dynamicChooseTest" resultType="User">    select * from user where sex = 'male'    <choose>          <when test="username != null">            and username like #{username}          </when>        <when test="phone != null">            and phone like #{phone}          </when>        <otherwise>            and address = 'chengdu'        </otherwise>    </choose></select>

3.trim(trim 元素可以给自己包含的内容加上前缀(prefix)或加上后缀(suffix),也可以把包含内容的首部(prefixOverrides)或尾部(suffixOverrides)某些内容移除。

<select id="dynamicTrimTest" resultType="User">      select * from user    <trim prefix="where" prefixOverrides="and |or ">          <if test="address != null">            address = #{address}          </if>          <if test="phone != null">            and phone like #{phone}          </if>    </trim></select>

4.where(where 元素知道只有在一个以上的 if 条件满足的情况下才去插入 where 子句,而且能够智能地处理 and 和 or 条件。

<select id="dynamicWhereTest" resultType="User">      select * from user    <where>          <if test="address != null">            address = #{address}          </if>          <if test="phone != null">            and phone like #{phone}          </if>    </where></select>

5.set(set 元素可以被用于动态包含需要更新的列,而舍去其他的。

<update id="dynamicSetTest">      update User    <set>          <if test="phone != null">phone=#{phone},</if>          <if test="address != null">address=#{address}</if>    </set>      where id=#{id}</update>

6.foreach(

foreach 元素常用到需要对一个集合进行遍历时,在 in 语句查询时特别有用。

foreach 元素的主要属性:

  • item:本次迭代获取的元素,当使用字典或者 Map 时,index 是键,item 是值
  • index:当前迭代的次数,当使用字典或者 Map 时,index 是键,item 是值
  • open:开始标志
  • separator:每次迭代之间的分隔符
  • close:结束标志
  • collection:该属性是必须指定的,在不同情况下,该属性的值是不一样的,主要有一下3种情况: 单参数且为 List 时,值为 list 单参数且为 array 数组时,值为 array 多参数需封装成一个 Map,map 的 key 就是参数名,collection 属性值是传入的 List 或 array 对象在自己封装的 map 里面的 key

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

原创粉丝点击