JAVA mybatis:mapper 中的动态SQL

动态SQL元素包括 if \ choose(when \ otherwise) \where \ set \foreach \bind

1.if

<select id="selectUsers" resultType="User">

  select * from users where state = 1

  <if test="id != null">     如果传入了id 参数,则加条件

     and id = #{id}

  </if>

</select>

对应的接口要进行相应设置

selectUsers(HashMap<String , Object>);  //HashMap 中包含id 来判断,也可以从javabean 中获取 property对象

多条件组合:

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

     and id = #{id} and name = #{name}

  </if>

2.choose(when \ otherwise)

<choose>

  <when test="id != null">

    and id = #{id}

  </when>

  <otherwise>

    and sex = 'male'

  </otherwise>

</choose>

对应接口的设置形式,和if一样。

3.where ,为组装条件,会自动对 连接符 进行舍去,避免组装的SQL 报错。

select * from users

<where>

  <if test="state != null">

      state = #{state}

  </if>

  <if test="id != null">

     id = #{id}

  </if>

</where>

4.set ,主要用于需更新的列

  <update id="user" parameterType="User">

     update  User

       <set>

           <if test="name != null">name=#{name}</if>

           <if test="sex != null">sex=#{sex}</if>

       </set>

     where id=#{id}

  </update>

5.foreach 

   select * from User where id in 

  <foreach item="item" index="index" collection="list" open="(" separator="," close=")">

      #{item}

  </foreach>

对应接口使用,list作为参数。

6.bind

<bind name="pattern" value="'%' + _parameter.getName() +'%'" />

SELECT * FROM User Where name like #{pattern}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值