解決Mybatis 報錯Invalid bound statement (not found)

  • 2021 年 10 月 23 日
  • 筆記

解決Mybatis 報錯Invalid bound statement (not found)

出現此錯誤的原因

1.xml文件不存在

2.xml文件和mapper沒有映射上

  • namespace指定映射mapper的路徑錯誤
  • id和mapper中的方法名不一致

image-20211023230835681

3.xml文件在java目錄下而不在resource目錄下,因此生成target中無xml

場景

​ 在使用Mybatis-plus框架時,自定義mapper介面和xm文件時,由於使用的是MP的自動生成程式碼插件,導致mapper介面和xml文件都在java目錄下,而在編譯時,在java路徑下的xml文件不會被自動編譯進去,編譯只會識別.java文件,只有在resource下的xml文件在打包時才能編譯進去。

下圖是MP自動生成程式碼插件的xml和mapper目錄(不再resource中)

image-20211023225723524

而編譯出來的target目錄下是這樣的:

image-20211023230007719

解決方法:

1.在pom文件中添加

    <build>
        <!-- 項目打包時會將java目錄中的*.xml文件也進行打包 -->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

2.手動將java目錄下的xml文件移到resource目錄下,並且在Spring Boot中的配置文件中加入

mybatis-plus:
	mapper-locations: classpath:**/*.xml //classpath後添加你xml文件的目錄

注意:部落客血的教訓!!!

mapper-locations中的目錄一定要是你放置xml文件的目錄一致,否則就算target中存在xml文件,也會出現這個錯誤!!!

由於本人能力有限,歡迎訪問個人部落格,進行技術交流,如有不足,歡迎指正~