XML中书写sql(动态SQL)

1.#{}与${}

#{}表示一个占位符,使用占位符可以防止sql注入,
$ {}通过${}可以将parameterType传入的内容拼接在sql中,不能防止sql注入,但是有时方便

例:

SELECT * FROM USER WHERE username LIKE '%${name}%'

再比如order by排序,如果将列名通过参数传入sql,根据传的列名进行排序,应该写为:

ORDER BY ${columnName}

如果使用#{}将无法实现此功能。

2.传递包装类型
public class UserVo {
    private Administration adm;  
    //自定义用户扩展类
    private UserCustom userCustom;
}
<select id="findUserList" parameterType="userVo" resultType="UserCustom">
          SELECT * FROM adm where adm.sex=
          #{userCustom.sex} and adm.username LIKE '%${userCustom.username}%'
</select>
3.动态sql

可以对输出参数进行判断,若果输入参数不为空,或是符合条件才进行sql拼接(where 子句能够自动消除第一个and-)

<sql id="search">
        t.del_flag = #{DEL_FLAG_NORMAL}
   <if test="sqlMap.search != null and sqlMap.search != ''">
     and (t.value like CONCAT('%',#{sqlMap.search},'%') or t.property like CONCAT('%',#{sqlMap.search},'%')or t.remarks like CONCAT('%',#{sqlMap.search},'%'))
   </if>
</sql>

<select id="countAll" resultType="int">
    select  
        count(*)
    from tag t 
     <where>
        <include refid="search" />
     </where>
</select>
4.foreach

使用foreach循环遍历
collection:指定集合的输入对象
item:每个遍历生成的对象
open:开始遍历时生成
close:结束遍历时生成
separator:遍历两个对象中间的拼

<update id="delete">
    update tag set
        update_date=now(),
        del_flag=#{delFlag}
    where id in 
   <foreach collection="ids" item="id" open="(" close=")" separator=",">
       #{id}
   </foreach>
</update>

再例

SELECT * FROM USER WHERE id=1 OR id=10 OR id=16
<where>
    <if test="ids != null">
      <foreach collection="ids" item="user_id" open="And ( " close=")" separator="OR">
        <!-- 每个遍历中所需拼接的字符串 -->
          id=#{user_id}
     </foreach>
    </if>
</where>
5.更新语句中if,和set

在这里,会根据标签中内容的有无来确定要不要加上set,同时能自动过来内容后缀逗号,但是有一点要注意,不同于,当中内容为空时,我们可以查出所有人的信息,但是这里更新语句中,内容为空时,语句变成update person

<update id="updatePerson1">
    update person
    <set>
     <if test="name != null">
            NAME = #{name},
        </if>
        <if test="gender != null">
            GENDER = #{gender},
        </if>
    </set>
</update>
6.选择choose
<choose>
   <when test="null != sort and '' != sort">
      order by ${sort}
   </when>
   <otherwise>
      order by id desc
   </otherwise>
</choose>
  • 11
    点赞
  • 62
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值