Mybatis模糊查询的三种写法

Mybatis中LIKE的三种写法

第一种写法:

 <select id="queryPersonList" resultMap="BaseResultMap">
        SELECT
          personName, personPassword, address
        FROM person_info
        <where>
            1=1
            <if test="personName != null and personName !=''">
                AND personName LIKE 
                "%${personName,jdbcType=VARCHAR}%"
            </if>
        </where>
    </select>

$符号可能导致SQL注入,不推荐。因为#{}是预编译处理,${}是字符串替换,Mybatis在处理#{}时,会将SQL中的#{}替换为?,

调用PreparedStatement的set方法来赋值;Mybatis在处理${}时,就是把${}替换成变量的值。

第二种写法:

<select id="queryPersonList" resultMap="BaseResultMap">
        SELECT
          personName, personPassword, address
        FROM person_info
        <where>
            1=1
            <if test="personName != null and personName !=''">
                AND personName LIKE 
                "%"#{personName,jdbcType=VARCHAR}"%"
            </if>
        </where>
    </select>

#{}在解析sql语句时候,在变量外侧自动加单引号'  ',因此这里 % 需要使用双引号"  ",不能使用单引号 '  ',否则会查不到任何结果。

第三种写法

<select id="queryPersonList" resultMap="BaseResultMap">
        SELECT
        personName, personPassword, address
        FROM person_info
        <where>
            1=1
            <if test="personName != null and personName !=''">
                AND personName LIKE 
                CONCAT('%', #{personName,jdbcType=VARCHAR}, '%')
            </if>
        </where>
    </select>

 使用CONCAT()函数连接参数形式,推荐使用这种方法。

posted @ 2021-07-27 12:43  北国浪子  阅读(2326)  评论(0编辑  收藏  举报