MyBatis 报错的原因有很多,不能一概而论,需要看具体的报错信息(异常堆栈) 才能精确定位。不过,我可以先给你总结 Java + MyBatis 最常见的报错原因和对应解决办法,你可以对照看看是哪一种。
Invalid bound statement (not found)原因:
namespace 写错id 不一致检查点:
<mapper namespace="com.example.mapper.UserMapper">
<select id="selectById" resultType="User">
✅ 接口:
User selectById(Integer id);
✅ 启动类或配置:
mybatis:
mapper-locations: classpath*:mapper/*.xml
BindingException: Parameter 'xxx' not found原因:
@Param错误:
User select(String name, Integer age);
XML:
where name = #{name}
✅ 正确写法:
User select(@Param("name") String name, @Param("age") Integer age);
SQLSyntaxErrorException原因:
示例:
select * from order -- order 是关键字
✅ 改成:
select * from `order`
TooManyResultsException原因:
User getUser();
但 SQL 返回了 2 条数据 ❌
✅ 改:
List<User> getUser();
Type interface xxx is not known to the MapperRegistry原因:
@Mapper 或 @MapperScan✅ 解决:
@Mapper
public interface UserMapper {}
或:
@MapperScan("com.example.mapper")
报错:
nullReflectionException✅ 开启驼峰:
mybatis:
configuration:
map-underscore-to-camel-case: true
或手动映射:
<result column="user_name" property="userName"/>
NullPointerException常见原因:
@Service / @Repository请把下面信息发我:
例如:
报错:Invalid bound statement
Mapper:UserMapper.selectById
XML 已放在 resources/mapper
如果你愿意,直接把报错贴出来,我可以一行一行帮你分析 ✅
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。