在ssm框架中,mybatis+spring操作数据库报错:org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.BindingException: Parameter 'category' not found. Available parameters are [arg1, arg0, param1, param2]
2021/7/21:其实就是方法参数名,到xml文件识别不了的问题今天又遇上了,错误点已标出
出错的代码:
- mapper
//通过书的种类或者书名模糊查询,查找相应的图书总数
public int queryProductsCount(String name, String category);
- mapper.xml
<!--通过书的种类或者书名模糊查询,查找相应的图书总数-->
<select id="queryProductsCount" resultType="int">
select count(1) as count from itcaststore.products
<where>
<if test="category != null">
category like concat('%',#{category},'%')
</if>
<if test="name != null">
and name like concat('%',#{name},'%')
</if>
</where>
</select>
- service
public int queryProductsCount(String name,String category);
- serviceImpl
public int queryProductsCount(String name,String category) {
return productsMapper.queryProductsCount(name,category);
}
- test
@org.junit.Test
public void test() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
ProductsServiceImpl productsServiceImpl = context.getBean("ProductsServiceImpl", ProductsServiceImpl.class);
System.out.println(productsServiceImpl.queryProductsCount(null,null));
}
错误原因
mybatis的Mapper接口方法传入了多个参数
还要注意:parameterType是要去掉的,虽然这里的参数全部都是String类型,如果涉及多个类型那就必须去掉
解决方法一:
使用#{arg0}和#{arg1}来告诉mybatis,当前变量使用哪个参数的值
<select id="queryProductsCount" resultType="int">
select count(1) as count from itcaststore.products
<where>
<if test="category != null">
category like concat('%',#{arg0},'%')
</if>
<if test="name != null">
and name like concat('%',#{arg1},'%')
</if>
</where>
</select>
但是因为这里有:<if test="category != null">和<if test="name != null">,所以此法对于这种特殊情况无解
解决方法二:(不修改mapper.xml)
使用注解@Param
public int queryProductsCount(@Param("name") String name, @Param("category")String category);
解决方法三:
HashMap类型作为传入类型(不修改mapper.xml)
public int queryProductsCount1(Map<String,String> map);
- Test
@org.junit.Test
public void mapperTest() {
//获取SqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
ProductsMapper mapper = sqlSession.getMapper(ProductsMapper.class);
Map<String,String> map = new HashMap<String,String>();
map.put("name",null);
map.put("category",null);
System.out.println(mapper.queryProductsCount1(map));
} catch (IOException e) {
e.printStackTrace();
}
}