MyBatis——动态sql标签

一,where、if标签

  • where 标签:可以自动判断是否要删除语句块中的 and 关键字(若where与and相连接则删除)
  • if 标签:可以自动根据表达式的结果来决定是否将对应的语句句添加到 SQL 中
	<select id="findByAccount" parameterType="com.lin.entity.Account" resultType="com.lin.entity.Account">
        select * from account
        <where>
            <if test="id!=0">
                id=#{id}
            </if>
            <if test="username!=null">
                and username=#{username}
            </if>
            <if test="password!=null">
                and password=#{password}
            </if>
            <if test="age!=0">
                and age=#{age}
            </if>
        </where>
    </select>

二、choose 、when

  • 若第一个when满足条件则不执行下面的when
  • 若没有一个when满足条件则执行otherwise
	<select id="findByAccount" parameterType="com.lin.entity.Account" resultType="com.lin.entity.Account">
        select * from account
		<where>
            <choose>
                <when test="id!=0">
                    id = #{id}
                </when>
                <when test="username!=null">
                    username = #{username}
                </when>
                <when test="password!=null">
                    password = #{password}
                </when>
                <when test="age!=0">
                    age = #{age}
                </when>
                <otherwise>
                    id=5
                </otherwise>
            </choose>
        </where>

三、trim

prefix:在最前加入
suffix:在最后加入
prefixOverrides:去掉前面第一个
suffixOverrides:去掉后面最后一个

<!-- 等同于where -->
<trim prefix="where" prefixOverrides="and">
<!-- update语句可使用 -->
<trim prefix="set" suffixOverrides=",">

四、set

逗号会自动处理

	<update id="update" parameterType="com.lin.entity.Account">
        update account
        <set>
            <if test="username!=null">
                username=#{username},
            </if>
            <if test="password!=null">
                password=#{password},
            </if>
            <if test="age!=0">
                age=#{age},
            </if>
        </set>
        where id=#{id}
    </update>

五、foreach标签

foreach 标签可以迭代生成一系列值,这个标签主要用于 SQL 的 in 语句。

select * from account where id in (1,2,3)
  <select id="findByIds" parameterType="com.lin.entity.Account"
          resultType="com.lin.entity.Account">
      select * from account
      <where>
          <foreach collection="ids" open="id in (" close=")" item="id"
                   separator=",">
              #{id}
          </foreach>
      </where>
  </select>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值