方式一:
<!-- 分页查询 -->
<select id="page" resultType="Map">
select ID as id,NAME as name, SEX as sex
from user where 1=1 and is_delete="1"
<if test='sex!=null and sex!=""'>and SEX= #{sex}</if>
<if test='name!=null and name!=""'>and NAME like #{name}</if>
</select>
不足:再测试的时候传入的参数需要前后加入%,比如:userMapper.selectList("男”,"%小%");
把性别为男和名字带有小的都 查询出来。
方式二:改进方式一中需要在参数加%的问题
<!-- 分页查询 -->
<select id="page" resultType="Map">
select ID as id,NAME as name, SEX as sex
from user where 1=1 and is_delete="1"
<if test='sex!=null and sex!=""'>and SEX= #{sex}</if>
<if test='name!=null and name!=""'>and NAME like '%${name}%'
</select>
为什么不是'%#{name}%'
,原因是加上单引号后会被当成是字符串,#{}写在字符串中不能被识别,因此换成了'%${name}%'
不足:'%${name}%'
是以拼接的方式生成sql语句,'%#{name}%'
是以占位符的方式生成sql语句,$会有sql注入的问题,因此需要改进。
方式三:改进方式二,使用mysql函数
<!-- 分页查询 -->
<select id="page" resultType="Map">
select ID as id,NAME as name, SEX as sex
from user where 1=1 and is_delete="1"
<if test='sex!=null and sex!=""'>and SEX= #{sex}</if>
<if test='name!=null and name!=""'>and NAME like concat('%',#{name},'%')</if>
</select>
方式四:
<!-- 分页查询 -->
<select id="page" resultType="Map">
select ID as id,NAME as name, SEX as sex
from user where 1=1 and is_delete="1"
<if test='sex!=null and sex!=""'>and SEX= #{sex}</if>
<if test='name!=null and name!=""'>and NAME like concat('%','${name}','%')</if>
</select>
总结:
1、#{ }是预编译处理,MyBatis在处理#{ }时,它会将sql中的#{ }替换为?,然后调用PreparedStatement的set方法来赋值,传入字符串后,会在值两边加上单引号,使用占位符的方式提高效率,可以防止sql注入。
2、${}:表示拼接sql串,将接收到参数的内容不加任何修饰拼接在sql中,可能引发sql注入。