XML中书写sql

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_43652509/article/details/102724753

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>

猜你喜欢

转载自blog.csdn.net/qq_43652509/article/details/102724753
今日推荐