解决一个mybatis的小问题
楼主本来在写一个小demo,接入数据库突然遇到了一个越界错误,反复检查也没有发现问题,最后在返回的实体类中发现了问题。

很简单的一个测试函数调用一下mapper

mapper

mapper.xml

启动方法就报了越界错误:org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException:
Error querying database. Cause: java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
The error may exist in com/pekah/common/mapper/LoginMapper.xml
The error may involve com.pekah.common.mapper.LoginMapper.getUser2
The error occurred while handling results
SQL: select * from user where username = ?
Cause: java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
原因:返回的User类中只有有参构造,所以在mybatis返回数据库时就无法自动映射为User对象。

解决方法:添加无参构造,或者是需要的有参构造
例如:只加一个无参构造

或者加入需要的有参构造

运行:得到查询结果

本文讲述了博主在使用MyBatis时遇到的越界错误,源于返回的User实体缺少构造器导致映射失败。解决方案包括添加无参构造或所需参数构造,以确保数据库查询结果能正确转换。
3321

被折叠的 条评论
为什么被折叠?



