org.apache.ibatis.binding.BindingException: Invalid bound statement (not found):

org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): xxx.xxx.xxx.service.ReDemoService.selectByPrimaryKey

spring boot 2.0 做 mybatis 多數據源配置出了以上錯誤:

網上給出3種解決方案:

1.xxxMapper.xml 中namespace和接口不一致導致.

2.MapperLocations沒有掃描到xml文件.

3.idea的坑,pom.xml配置resource將xml文件打包的時候加入到類路徑下

可是~... 3種都試了.都不能解決bug.最後發現一個問題

ReDemoService.selectByPrimaryKey() .service接口怎麼被mybatis註冊爲映射接口了


針對如圖目錄結構. 所以在整合掃包的時候要強制限定掃描規則

java bean 配置方式

@Configuration
@MapperScan(basePackages = "com.mm2s",annotationClass = Mapper.class) // 需要在接口上加上Mapper註解
//@MapperScan(basePackages = "**.mapper")
public class MybatisReConfig {

    @Primary
    @Bean("reDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.h2-re")
    public DataSource reDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public SqlSessionFactory reSqlSessionFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(reDataSource());
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        factoryBean.setMapperLocations(resolver.getResources("classpath:mybatis/ReMappings/**/*Mapper.xml"));
        factoryBean.setConfigLocation(resolver.getResource("classpath:mybatis/mybatis-config.xml"));
        return factoryBean.getObject();
    }

    @Bean
    @Primary
    public SqlSessionTemplate reSqlSessionTemplate() throws Exception {
        return new SqlSessionTemplate(reSqlSessionFactory());
    }

}

xml 配置方式

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
          p:dataSource-ref="dataSource"
          p:mapperLocations="classpath:mybatis/mappers/*.xml">
    </bean>

	<!-- 掃描項目包下含有Mapper註解的類作爲mybatis的映射接口-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
          p:basePackage="com.mm2s"
          p:annotationClass="org.apache.ibatis.annotations.Mapper"
          p:sqlSessionFactoryBeanName="sqlSessionFactory"/>
		  
	<!-- 掃描名爲mapper包下的類作爲mybatis的映射接口  
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
          p:basePackage="**.mapper"
          p:sqlSessionFactoryBeanName="sqlSessionFactory"/> -->

解決方法4: 

   @MapperScan中加入掃包限定annotationClass = Mapper.class  在xxxMappr加入@Mapper

   @MapperScan掃描包名爲mapper下的類 basePackages = "**.mapper"

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