温馨提示×

温馨提示×

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

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

java mybatis为何报绑定错误

发布时间:2026-09-02 18:07:16 来源:亿速云 阅读:92 作者:小樊 栏目:编程语言

在 Java + MyBatis 中,**“绑定错误”**最常见的是下面这类异常:

org.apache.ibatis.binding.BindingException:
Invalid bound statement (not found): xxx.xxx.Mapper.xxxMethod

意思就是:Mapper 接口里的方法,找不到对应的 SQL 映射

下面按最常见原因 → 解决方案给你总结:


一、Mapper 接口和 XML 没对上(最常见)

1️⃣ namespace 写错

XML 中的 namespace 必须等于 Mapper 接口全限定名

❌ 错误示例:

<mapper namespace="com.demo.mapper.User">

✅ 正确:

<mapper namespace="com.demo.mapper.UserMapper">

2️⃣ 方法名不一致

接口方法名 ≠ XML 中的 id

接口:

User selectById(Long id);

XML:

<select id="selectByID" resultType="User">

selectByIDselectById


3️⃣ parameterType / resultType 错

虽然不是“绑定错误”主因,但常一起出现:

  • resultType 写成不存在的类
  • 包名写错

二、XML 文件没被扫描到(非常常见)

1️⃣ Maven 没打包 XML

src/main/java 下的 XML 默认不会被打包

✅ 解决:

<build>
  <resources>
    <resource>
      <directory>src/main/java</directory>
      <includes>
        <include>**/*.xml</include>
      </includes>
    </resource>
  </resources>
</build>

或把 XML 放到:

resources/mapper/xxxMapper.xml

2️⃣ MyBatis 没配置 mapper 位置

MyBatis 原生:

<mappers>
  <mapper resource="mapper/UserMapper.xml"/>
</mappers>

Spring Boot:

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

三、Mapper 接口没被注册

Spring / Boot 场景

❌ 忘记加注解或扫描

✅ 解决方式之一:

@Mapper
public interface UserMapper {}

或:

@MapperScan("com.demo.mapper")

四、方法返回类型不匹配(少见但会误报)

例如:

List<User> list();

XML 却写成:

<select id="list" resultType="User">

✅ 实际是对的
❌ 如果写成 resultType="map" 可能间接导致问题


五、使用了错误的方式调用

❌ 直接 new Mapper

UserMapper mapper = new UserMapper();

✅ 必须通过 SqlSession 或 Spring 注入


六、快速自查清单 ✅

你可以按顺序查:

  1. XML namespace = 接口全类名
  2. id = 接口方法名
  3. XML 在 classpath
  4. mapper-locations 配置正确
  5. 接口被 @Mapper@MapperScan 扫描
  6. 项目重新 build / clean

如果你愿意,可以把:

  • 报错完整信息
  • Mapper 接口
  • XML 文件
  • 项目结构

贴出来,我可以直接帮你定位是哪一条

向AI问一下细节

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

AI