问题描述:
在使用Mybatis注解配置模糊查询时,发生了org.apache.ibatis.type.TypeException
的异常。之前对其他的CRUD进行测试都正常
详细的问题信息:
org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: org.apache.ibatis.type.TypeException: Could not set parameters for mapping: ParameterMapping{property='name', mode=IN, javaType=class java.lang.String, jdbcType=null, numericScale=null, resultMapId='null', jdbcTypeName='null', expression='null'}. Cause: org.apache.ibatis.type.TypeException: Error setting non null for parameter #2 with JdbcType null . Try setting a different JdbcType for this parameter or a different configuration property. Cause: java.sql.SQLException: Parameter index out of range (2 > number of parameters, which is 1).
### The error may exist in com/dao/UserDao.xml
### The error may involve com.dao.UserDao.findUserByName-Inline
### The error occurred while setting parameters
### SQL: -- select * from user where name like ? select * from user where username like ?
### Cause: org.apache.ibatis.type.TypeException: Could not set parameters for mapping: ParameterMapping{property='name', mode=IN, javaType=class java.lang.String, jdbcType=null, numericScale=null, resultMapId='null', jdbcTypeName='null', expression='null'}. Cause: org.apache.ibatis.type.TypeException: Error setting non null for parameter #2 with JdbcType null . Try setting a different JdbcType for this parameter or a different configuration property. Cause: java.sql.SQLException: Parameter index out of range (2 > number of parameters, which is 1).
相关的代码:
User.java中的相关代码:
private Integer id;
private String username;
private String address;
private String sex;
private Date birthday;
UserDao.xml中的配置信息为:
<select id="findUserByName" parameterType="string" resultType="com.domain.User">
-- select * from user where name like #{name}
select * from user where username like #{name}
</select>
MybatisTest.java中的相关代码为:
@Test
public void testFindUserByName(){
List<User> users = userDao.findUserByName("%王%");
for (User user : users) {
System.out.println(user);
}
}
解决方法:
咋一看感觉没有什么明显的错误,在UserDao.xml中的name也换成了username进行sql语句查询,后来发现,是这行写错了的sql语句的注释有误,xml中的注释需要 <!-- -->
引起,不能用 --
。我删掉这行注释或者用 <!-- -->
注释掉写错的sql语句,就可以正常运行了。