MyBatis注解开发中传多参问题

版权声明:LiuK°版权所有 https://blog.csdn.net/weixin_43401946/article/details/83650041

在Mybatis中使用注解开发时传入多参会遇到这样的错误:
代码如下:

//接口代码
	/**
     * 模糊查询
     * @param name
     * @return
     */
    @Select("select * from user where username like '%${name}%' and sex=#{sex}")
    public List<User> findByName(String name, String sex);
//测试类代码
@Test
    public void TestfindByName(){
        List<User> users = userDao.findByName("王","男");
        for (User user : users) {
            System.out.println(user);
        }
    }

报错信息如下:
org.apache.ibatis.exceptions.PersistenceException:

Error querying database. Cause: org.apache.ibatis.binding.BindingException: Parameter ‘name’ not found. Available parameters are [arg1, arg0, param1, param2]
Cause: org.apache.ibatis.binding.BindingException: Parameter ‘name’ not found. Available parameters are [arg1, arg0, param1, param2]

出现这种情况是因为传入多参时在注解中并不能识别,所以解决办法有两个:
第一种:在注解中使用参数时直接使用param1、param2、、、、这样会自动识别。

 /**
     * 模糊查询
     * @param name
     * @return
     */
    @Select("select * from user where username like '%${param1}%' and sex=#{param2}")
    public List<User> findByName(String name, String sex);

第二种办法:如果你不想使用第一种,想直接使用自己定义的参数名如下,在定义接口时直接注解他为参数。

 @Select("select * from user where username like #{name} and sex=#{sex}")
    public List<User> findByNameTwo(@Param("name") String name, @Param("sex") String sex);

猜你喜欢

转载自blog.csdn.net/weixin_43401946/article/details/83650041