温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java mybatis为啥报错

发布时间:2026-10-13 21:57:39 来源:亿速云 阅读:109 作者:小樊 栏目:编程语言

MyBatis 报错的原因有很多,不能一概而论,需要看具体的报错信息(异常堆栈) 才能精确定位。不过,我可以先给你总结 Java + MyBatis 最常见的报错原因和对应解决办法,你可以对照看看是哪一种。


一、最常见 MyBatis 报错场景

1️⃣ Invalid bound statement (not found)

原因:

  • Mapper 接口和 XML 没对应上
  • XML 中 namespace 写错
  • 方法名和 id 不一致
  • XML 没被扫描到

检查点:

<mapper namespace="com.example.mapper.UserMapper">
    <select id="selectById" resultType="User">

✅ 接口:

User selectById(Integer id);

✅ 启动类或配置:

mybatis:
  mapper-locations: classpath*:mapper/*.xml

2️⃣ BindingException: Parameter 'xxx' not found

原因:

  • 方法有多个参数,但 XML 没用 @Param

错误:

User select(String name, Integer age);

XML:

where name = #{name}

✅ 正确写法:

User select(@Param("name") String name, @Param("age") Integer age);

3️⃣ SQLSyntaxErrorException

原因:

  • SQL 写错
  • 表名 / 字段名不存在
  • 数据库关键字未加反引号

示例:

select * from order  -- order 是关键字

✅ 改成:

select * from `order`

4️⃣ TooManyResultsException

原因:

  • 方法返回类型是对象,但 SQL 查出了多条
User getUser();

但 SQL 返回了 2 条数据 ❌

✅ 改:

List<User> getUser();

5️⃣ Type interface xxx is not known to the MapperRegistry

原因:

  • Mapper 接口没被扫描
  • 没加 @Mapper 或 @MapperScan

✅ 解决:

@Mapper
public interface UserMapper {}

或:

@MapperScan("com.example.mapper")

6️⃣ 数据库字段和实体类不匹配

报错:

  • 查出来是 null
  • 或 ReflectionException

✅ 开启驼峰:

mybatis:
  configuration:
    map-underscore-to-camel-case: true

或手动映射:

<result column="user_name" property="userName"/>

7️⃣ NullPointerException

常见原因:

  • Mapper 没注入(@Autowired 为 null)
  • 没加 @Service / @Repository
  • 自己 new Mapper(❌)

二、你可以这样发我,我能精准帮你

请把下面信息发我:

  1. 完整报错信息(异常堆栈)
  2. Mapper 接口代码
  3. XML 或注解 SQL
  4. 实体类(可选)
  5. MyBatis 配置(yml / xml)

例如:

报错:Invalid bound statement
Mapper:UserMapper.selectById
XML 已放在 resources/mapper


如果你愿意,直接把报错贴出来,我可以一行一行帮你分析 ✅

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手