mybatis 查询返回值映射异常
-
- 具体异常
- 异常理解
- 解决方法
具体异常
org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: org.apache.ibatis.executor.result.ResultMapException: Error attempting to get column 'name' from result set. Cause: java.sql.SQLException: Invalid value for getInt() - '张三'
### The error may exist in com/conlin/mapper/UserMapper.xml
### The error may involve com.conlin.mapper.UserMapper.findAll
### The error occurred while handling results
### SQL: select * from mybatis.user
### Cause: org.apache.ibatis.executor.result.ResultMapException: Error attempting to get column 'name' from result set. Cause: java.sql.SQLException: Invalid value for getInt() - '张三'
异常理解
异常信息表示,在查询结果中name值映射为int类型的值,如下:
原因是在实体中加了有参的构造方法,而未实现无参构造方法或全参构造方法。
解决方法
这个异常主要是因为实体属性与sql结果无法对应导致。
1、实现无参构造或全参构造,这样用
select * from mybatis.user
这个sql 查出所用字段将与user属性一一对应。
2、在SQL中将 * 替换为需要的字段,与实体中的构造方法参数对应,如下:
<select id="findAll" resultType="com.conlin.entity.User">
select name,age from mybatis.user
</select>
public User(String name, int age) {
this.name = name;
this.age = age;
}
这样的话也可以解决上面的异常,但是查询结果映射为实体后,其他没有对应的字段将为空值。