首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

MyBatis映射文件Namespace配置錯誤導致insert失敗解決方案

     編輯:程式設計綜合問答

錯誤信息

Cause: java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for com.baosight.webapp.sqlmap.addPro

根本原因

MyBatis 根據 `` 定義的命名空間 + 语句ID(如`insert`標簽的`id`屬性)構建唯一鍵。報錯說明:

  • Mapper接口方法對應的XML語句未被解析/註冊
  • 常見原因:`namespace`值與Mapper接口**全限定名不一致**

排查清單

  1. 檢查Mapper接口:
    package com.baosight.webapp.dao;
    public interface UserMapper {
        void addPro(User user);
    }
  2. 檢查XML映射文件(通常命名為`UserMapper.xml`,置於同包下resources目錄):
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.baosight.webapp.dao.UserMapper">  <!-- 必須與接口全限定名完全一致 -->
        <insert id="addPro" parameterType="com.baosight.webapp.entity.User">
            INSERT INTO t_user (name, age) VALUES (#{name}, #{age})
        </insert>
    </mapper>
  3. 檢查MyBatis配置掃描路徑(`mybatis-config.xml` 或 Spring集成配置):
    <!-- 掃描mapper XML文件 -->
    <mappers>
        <package name="com.baosight.webapp.dao"/>
    </mappers>
    <!-- 或 Spring集成 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.baosight.webapp.dao"/>
    </bean>

快速定位技巧

  • 啟動項目時觀察控制台日誌,MyBatis會打印解析到的Mapped Statements鍵值
  • 在報錯處打斷點,查看`Configuration.getMappedStatementNames()`集合內容
  • 使用MyBatis Generator生成代碼,避免手寫錯誤

總結

Namespace = Mapper接口全限定名,這是MyBatis映射註冊的核心約定。任何拼寫錯誤、包名變更未同步、XML未被掃描,都會導致「Mapped Statements collection does not contain value」錯誤。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved