【Mybatis】- 模糊查询方式汇总- 分析

832 阅读1分钟

Mybatis- 模糊查询

1.传入接口的字符串拼接"%like%" --使用#{...}

动态解析 -> 预编译 -> 执行

  1. 没有在Mapper文件拼接%的情况
<!-- 根据名称模糊查询 --> 
<select id="findByName" resultType="com.newzhong.pojo.User" parameterType="String">
	<if test="userName != null and userName != ''">
		select * from user where username like #{username}
	</if>
</select>

因为在Mapper中没有进行%拼接,所以需要在接口传参数拼接,程序代码中就需要加入模糊查询的匹配符%

select * from user where username like "%username%";

2. 使用${...},直接和SQL语句拼串,动态解析 -> 编译 -> 执行

<select id="findByName" parameterType="string" 	resultType="com.newzhong.pojo.User">
<if test="userName != null and userName != ''">
	select * from user where username like '%${value}%'
   <!--select * from user where username like '%${userName,jdbcType=VARCHAR}%' 无法加类型--> 
</if>
</select>

注意:1. 由于$是参数直接注入的,导致这种写法,大括号里面不能加上jdbcType,也有可能会引起sql的注入


注意: 2. ${自定义参数名} 如果使用自定义参数名,需要在映射器接口方法的参数前加注解@Param("")来与配置文件进行映射,否则只能使用MyBatis 默认值 value,即 ${value}

<select id="findByName" parameterType="string"  resultType="com.newzhong.pojo.User">
<if test="userName != null and userName != ''">
    select * from user where username like '%${userName}%'
</if>
</select>
User findByName(@Param("userName") String userName);

3. 使用<bind>标签实现

 <select id="findByUserName" resultType="com.newzhong.pojo.User" parameterType="string">
 	select * from PERSON
    	<!--接口传入的值在name变量中,然后把传入的值拼接成"'%'+name+'%'"形式,放入userName参数中-->
        <bind name="userName" value="'%'+name+'%'"/>
        <if test="userName!= null and userName != ''">
            where userName like #{userName}
        </if>
    </select>

注意:在标签里将参数拼接糊查询的匹配符%,然后放入name里面,在if里面使用name里面的参数;

4. 使用函数concat,可以方式sql注入

<select id="findByName" parameterType="string" resultType=""com.newzhong.pojo.User">
<if test="userName != null and userName != ''">
    select * from user where username like concat('%',#{username},'%')
</if>
</select>

5. 使用instr()也可以达到效果

格式一

instr( string1, string2 )    // instr(源字符串, 目标字符串)
<select id="findByName" parameterType="string" resultType=""com.newzhong.pojo.User">
<if test="userName != null and userName != ''">
    select * from user where instr(userName,#{userName}) > 0;
</if>
</select>

效率还挺高的,也没有sql注入