天天看點

MyBatis 模糊查詢like 的三種方式

方式一、拼接傳參法

首先在調用DAO前,對需要模糊查詢的參數進行拼接

if (!StringUtils.isEmpty(appName)) {
            appName = "%" + appName + "%";
        }
           

然後DAO.xml中直接使用 like #{param} 的方式,如下:

<select id="selectAllApp" resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List"/>
    from app
    <if test="appName != null and appName != ''">
        where app_name like #{appName,jdbcType=VARCHAR}
    </if>
</select>
           

方式二、mysql的CONCAT()函數

直接使用concat()函數:

<select id="selectAllApp" resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List"/>
    from app
    <if test="appName != null and appName != ''">
        where app_name like CONCAT('%',#{appName,jdbcType=VARCHAR},'%')
    </if>
</select>
           

方式三、Mybatis的bind标簽

<select id="selectAllApp" resultMap="BaseResultMap">
    <bind name="pattern" value="'%' + appName + '%'" />
    select
    <include refid="Base_Column_List"/>
    from app
    where app_name like #{pattern}
</select>
           

【注意】還有一種是直接使用like '%${appName}%',這種方式會直接傳值,無法防止sql注入攻擊,不推薦使用!!