天天看点

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注入攻击,不推荐使用!!