Parameter index out of range的一些处理方法
最近项目开发的时候,出现了一个很怪异的BUG,Mybatis报Parameter index out of range异常,参数越界,就是说,参数数量和SQL语句的?占位符数量不一致,首先确定Mapper层的方法参数数量正确之后,对SQL语句进行检查
select * from student where sex = #{sex} and sname like '#{sname}%'
List<Student> selectStudentByParam(int sex ,String sname);
我的Mapper层是只有2个参数,这个sql语句里也是2个“#”,百度得到,在MyBatis中,like语句需要这么写
select * from student where sex = #{sex} and sname like '${sname}%'
但是把#换成$符号会导致SQL注入问题,所以使用CONCAT方法,字符串拼接,所以有下面这种写法
select * from student where sex = #{sex} and sname like CONCAT(CONCAT('%',#{sname,jdbcType=VARCHAR}),'%')
但是到头来,还是报这个异常…
此时我的MyBatis的这个sql语句是这样的
<select id="selectStundentByPara" resultType="com.bean.Student">
-- select * from student where sex = #{sex} and sname like '${sname}%'
select * from student where sex = #{sex} and sname like CONCAT(CONCAT('%',#{sname,jdbcType=VARCHAR}),'%')
</select>
还是一直报错一直报错…后来回去把xml文件里的下面这行这个注释删了…
-- select * from student where sex = #{sex} and sname like '${sname}%'
成功了…
我真不知道是啥情况,我的理解是,在MyBatis里对于SQL的注释,虽然在xml文件中使用 - - 注释,
但是 注释的语句里,如果有#{arg}或者${arg},MyBatis会把他认为是占位符"?",即使它已经被注释掉了
,所以会认为有4个?占位符,而你只给了2个参数…
所以,虽然说代码写注释是个好习惯,但是遇到这种事,谁说得清呢?