org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)
核心原因:**Mapper 介面與 XML 映射檔的對應關係斷裂**。
XML 檔案所在套件路徑必須與 Mapper 介面完全一致。
// 介面
package com.example.mapper;
public interface UserMapper { ... }
src/main/resources/com/example/mapper/UserMapper.xml
<mapper namespace="com.example.mapper.UserMapper">
Namespace 必須是 Mapper 介面的**完整限定名**,區分大小寫。
// 介面
User selectById(@Param("id") Long id);
<select id="selectById" resultType="User">
SELECT * FROM user WHERE id = #{id}
</select>
id 屬性必須與介面方法名**完全相同**。
#{paramName} 或 #{ }@Param("name"),XML 使用 #{name}#{username}現象:原始碼目錄有 XML,但 target/classes 下沒有對應的 Mapper XML。
解決:在 pom.xml 中配置資源過濾:
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
</build>
或將 XML 統一放置於 src/main/resources 目錄結構中(推薦)。
logging.level.com.example.mapper=DEBUG,觀察實際執行的 SQL 與綁定情況typeAliasesPackage 是否涵蓋實體類別@MapperScan("com.example.mapper") 或 XML <package> 配置mvn clean compile 或 IDE Invalidate Caches / Restart| 檢查項目 | 正確範例 | 常見錯誤 |
|---|---|---|
| Namespace | com.example.mapper.UserMapper | 漏寫 package、大小寫不符 |
| 方法名/id | selectById | selectByID、select_by_id |
| 參數綁定 | #{id} 對應 @Param("id") | 多參數未加 @Param |
| XML 輸出目錄 | target/classes/com/example/mapper/UserMapper.xml | 僅在 src 目錄,未編譯輸出 |
| ResultType | com.example.entity.User | 寫簡短類名、別名未配置 |
90% 的 BindingException 歸因於 **Namespace、方法名、參數綁定、資源輸出** 四大類問題。建立標準化的 Mapper 開發規範(套件結構、命名慣例、資源配置),可從源頭杜絕此類錯誤。