spring boot 多模块项目整合 mybatis 时提示找到不 Mapper 的解决方案

6,264 阅读1分钟

版本信息:

Spring Boot 2.1.3.RELEASE

问题一:找不到 Mapper Bean

错误信息:

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
01:56:25.921 logback [main] ERROR o.s.b.d.LoggingFailureAnalysisReporter - 

***************************
APPLICATION FAILED TO START
***************************

Description:

A component required a bean of type 'com.example.boss.admin.dao.mapper.SeckillMapper' that could not be found.


Action:

Consider defining a bean of type 'com.example.boss.admin.dao.mapper.SeckillMapper' in your configuration.

原因:

Mapper.java 和 Mapper.xml 放在不同的 jar 包工程里,默认情况下 mybatis 只读取同一个工程里的 Mapper Bean,即便加上了 @Mapper 注释也不行。

解决方法:

在 DataSourceConfig 里增加一个 bean 来处理

	/**
	 * Mapper接口所在包名,Spring会自动查找其下的Mapper
	 *
	 * @return mapperScannerConfigurer
	 */
	@Bean
	public MapperScannerConfigurer mapperScannerConfigurer() {
		MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
		mapperScannerConfigurer.setBasePackage("**.mapper");
		mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");

		return mapperScannerConfigurer;
	}

问题二:找不到 Mapper.xml

错误信息:

原因:

默认情况下,Mapper.xml 文件是放在 src/main/resources 目录下的,但由于用了 mybatis generator 的原因,把 xml 放在了 src/main/java 目录下,方便生成和管理。

解决方法:

在项目的 pom.xml 增加以下配置

        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
            <!-- resources配置解决mybatis 的mapperXml配置在java路径不被扫描的问题 -->
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>

问题三:如何读取多个模块项目下的 Mapper.xml 文件?

解决方法:

解决办法就是在classpath后加一个*就解决了,如

mybatis:
    mapper-locations: classpath*:mapper/*.xml