前言
當我們在開發過程中,由於maven項目本身的限制,我們不能直接把我們的mapper.xml文件和對應mapper.java接口文件放到一起,也就是不能直接放在java包中,如圖:
因為maven項目在構建打包時,會從src/main/java中獲取所有的java文件然后編譯,會從src/main/resources中獲取配置文件等其它文件,然后打包,
所以盡管你在Spring整合Mybatis時配置也好,在Mybatis單獨的配置文件中配置也好,都是會出錯的:
<!--配置SqlSessionFactory工廠--> <bean id="sqlSessonFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 掃描sql配置文件:mapper需要的xml文件 --> <property name="mapperLocations" value="classpath*:com/ssm/mapper/mapping/*.xml" /> </bean> <!--配置mapper接口所在包--> <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.ssm.mapper"/> </bean>
都是不會成功的!
方法:
這個時候你可以改變一下maven在打包時的配置就可以實現了:
在pom.xml文件中添加配置:
<!--插件配置--> <build> <resources> <resource> <directory>src/main/java</directory> <!--包含了src/main/java目錄下的所有xml資源配置文件--> <includes> <include>**/*.xml</include> </includes> </resource> <resource> <directory>src/main/resources</directory> <includes> <!--包含了src/main/resources目錄下的所有資源配置文件,有別的格式的配置文件時,不要寫成**/*.xml--> <include>**/*</include> </includes> <filtering>false</filtering> </resource> </resources> </build>
這個時候你就可以成功配置了!
附錄:
感謝以下博客:
https://blog.csdn.net/qq_38727626/article/details/81431522
還有就是:
其實下面這篇博客寫的也挺好,但是我發生報錯,就是你的resources目錄下的文件可能會出問題,
https://blog.csdn.net/weixin_30820077/article/details/97407662