SSM框架中写sql在xml文件中

第一种(用Mapper.xml映射文件中定义了操作数据库sql)

注意点:

1.#{}与${}

#{}表示一个占位符,使用占位符可以防止sql注入,

${}通过${}可以将parameterType传入的内容拼接在sql中,不能防止sql注入,但是有时方便

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

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

ORDER BY${columnName}

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

2.传递包装类型

public class QueryVo {
    
    private User user;
    
    //自定义用户扩展类
    private UserCustom userCustom;
<select id="findUserList" parameterType="queryVo" resultType="UserCustom">
            SELECT * FROM USER where user.sex=#{userCustom.sex} and user.username LIKE '%${userCustom.username}%'
 </select>

3.动态sql

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

    <select id="countAll" resultType="int">
        select  
            count(*)
        from tag t 
        <where>
            <include refid="search" />
        </where>
    </select>
<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>

4.foreach

    <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>

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

在例

SELECT * FROM USER WHERE id=1 OR id=10 ORid=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

<update id="updatePerson1">
    update person
    <set>
     <if test="name != null">
            NAME = #{name},
        </if>
        <if test="gender != null">
            GENDER = #{gender},
        </if>
    </set>
</update>

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

原文地址:https://www.cnblogs.com/G-JF/p/9305065.html