异常代码:HTTP Status 500 - Request processing failed; nested exception is org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.BindingException: Parameter ‘userId’ not found. Available parameters are [arg1, arg0, param1, param2]
原因是给用户添加多个角色信息时候出现的问题代码如下:
@Insert("insert into users_role(userId,roleId) values (#{userId},#{roleId}) ")
void addRoleToUser(int userId, int roleId);
弄清楚了原因,因为多个值的获取,需要指明具体的参数引用 所以需要使用@Param属性。
首先清除@Param的作用
- @Param注解的作用是给参数命名,参数命名后就能根据名字得到参数值,正确的将参数传入sql语句中(一般通过#{}的方式,${}会有sql注入的问题)。
- 当你使用了使用@Param注解来声明参数时,如果使用 #{} 或 ${} 的方式都可以,当你不使用@Param注解来声明参数时,必须使用使用 #{}方式。如果使用 ${} 的方式,会报错。
修改后的代码
@Insert("insert into users_role(userId,roleId) values (#{userId},#{roleId}) ")
void addRoleToUser(@Param("userId")int userId, @Param("roleId")int roleId);