一、在测试update时,传入多个参数,进行测试,发现一直报:
org.apache.ibatis.exceptions.PersistenceException:
### Error updating database. Cause: org.apache.ibatis.binding.BindingException:
Parameter '0' not found. Available parameters are [arg1, arg0, param1, param2]
### The error may involve defaultParameterMap
### The error occurred while setting parameters
### SQL: update students set name=? where stud_id=?
### Cause: org.apache.ibatis.binding.BindingException:
Parameter '0' not found. Available parameters are [arg1, arg0, param1, param2]
二、还原代码情景
1)、接口类StudentManager.java
public interface StudentMapper {
void updateStudentName(String name ,String id);
}
2)、映射文件StudentMapper.xml
<update id="updateStudentName">
update students set name=#{0} where stud_id=#{1}
</update>
PS:顺序#{0}和Mapper接口中的参数顺序一致
3)、测试代码
@Test
public void updateStudentName() {
SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
try {
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
studentMapper.updateStudentName("大牛",2);
sqlSession.commit();//提交,事务管理
} finally {
sqlSession.close();
}
}
三、参考了多个度贴,内容基本一样,结果无法
四、解决方案
4.1 研究错误异常
org.apache.ibatis.exceptions.PersistenceException:
### Error updating database. Cause: org.apache.ibatis.binding.BindingException:
Parameter '0' not found. Available parameters are [arg1, arg0, param1, param2]
### The error may involve defaultParameterMap
### The error occurred while setting parameters
### SQL: update students set name=? where stud_id=?
### Cause: org.apache.ibatis.binding.BindingException:
Parameter '0' not found. Available parameters are [arg1, arg0, param1, param2]
其中
Available parameters are [arg1, arg0, param1, param2]
含义是有效的参数是[arg1,arg0,param1,param2]
4.2 实质系统是通过map的方式进行自动绑定
其map对应的key就是上面的这些值[arg1,arg0,param1,param2]
代码中可以通过这些名字进行引用使用
<update id="updateStudentName">
update students set name=#{arg0} where stud_id=#{arg1}
</update>
或
<update id="updateStudentName">
update students set name=#{param1} where stud_id=#{param2}
</update>
弊端:魔术参数名!arg0,arg1,param1,param2
五、其他解决办法
5.1 在每个参数处设置@param("参数名")
public interface StudentMapper {
void updateStudentName(@param("name1") String name,@param("id1") String id);
}
5.2 在mapper.xml中使用设置的参数名
<update id="updateStudentName">
update students set name=#{name1} where stud_id=#{id1}
</update>
5.3 此时数据正常,可以正常执行,参数名也很舒服
六、源码sql脚本
上传资源时候忘了传,补上内容。
DROP TABLE IF EXISTS `students`;
CREATE TABLE `students` (
`stud_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`email` varchar(50) NOT NULL,
`dob` date DEFAULT NULL,
PRIMARY KEY (`stud_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
ps:源码下载 https://download.csdn.net/download/u011698550/10430282