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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值