SSM-Mybatis-动态SQL-trim、where、set

SSM-Mybatis-动态SQL-trim,where,set

where:

会在子元素返回任何内容情况下插入where字句,且子句的开头为 AND 或者 OR ,where元素也会将他们去除

<select id="findActiveBlogLike" resultType="Blog">
  SELECT * FROM BLOG
  <where>
     <!--子句开头如果是AND 或者 OR 会去除-->
    <if test="state != null">
         state = #{state}
    </if>
      
    <if test="title != null">
        AND title like #{title}
    </if>
      
    <if test="author != null and author.name != null">
        AND author_name like #{author.name}
    </if>
      
  </where>
</select>

trim:

​ 有时候去掉的是一些特殊的SQL语法,如 AND OR等,使用trim也可以达到预期

<select id="findRoles" parameterType="string" resultMap="roleResultMap">
    select role_no,role_name,note from t_role
    <trim prefix="where" prefixOverrides="and">
        <if test="roleName !=null and roleName !=''">
            and role_name like concat('%',#{roleName},'%')
        </if>
    </trim>
</select>

prefix:代表语句的前缀

prefixOverrides:代表需要去除掉的哪种字符串

set:

用于动态更新语句的类似解决方案叫做 setset 元素可以用于动态包含需要更新的列,忽略其它不更新的列。比如:

<update id="updateAuthorIfNecessary">
  update Author
    <set>
      <if test="username != null">username=#{username},</if>
      <if test="password != null">password=#{password},</if>
      <if test="email != null">email=#{email},</if>
      <if test="bio != null">bio=#{bio}</if>
    </set>
  where id=#{id}
</update>

这个例子中,set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值