springboot整合mybatis錯誤 Invalid bound statement (not found): 解決辦法

原因解析:

mapper 層的 Mapper 接口與 xml 文件映射出現問題、或 mapper 接口直接找不到xml文件。

解決方法:

一、查看 target 下是否打包了 xml 文件。

有一種情況是 xml 文件沒有放在 resources 目錄下,而放在了java包下,導致打包後 target/class 目錄下沒有 xml文件。

解決:pom.xml 中添加:

<resources>
            <resource>
                <directory>src/main/java</directory>
                <!-- 此配置不可缺,否則mybatis的Mapper.xml將會丟失 -->
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <!--指定資源的位置-->
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.yml</include>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>

二、查看 xml文件中 namespace 與 接口是否對應正確,id 與方法名是否對應

三、如果以上都沒有問題,那麼再查看 application.yml 中關於 mybatis 的配置。

敲黑板!!!
敲黑板!!!

注意兩點:
1、mybatis: 是頂層元素,所謂頂層元素,就是在頁面最左邊,前面不要有空格、不然會被包含在前面一個大塊中
(我被這麼個細節折磨了好久)

2、儘量用 classpath* 不要用 classpath
classpath:只會到你指定的class路徑中查找文件;
classpath*:不僅包含class路徑,還包括jar文件中(class路徑)進行查找

#mybatis:
mybatis:
  mapperLocations: classpath*:/com/user/mappers/*.xml

四、終極解決辦法

將 mapper 層接口與 xml 文件的路徑保持一致。這樣可以直接免去 application.yml 中的配置,
在打包時會將xml文件打包到 mapper 接口所在的包下。
如下圖:

在這裏插入圖片描述

這樣出錯得概率最小

注:一些博客上分析在 入口處使用 @MapperScan 註解,這個註解是爲了 掃描 mapper層接口的,不能解決這個問題。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章