如何在多数据源环境中使用Spring Boot application.yml的mybatis.mapper-locations选项?

时间:2019-02-07 07:20:56

标签: spring-boot datasource mybatis

如何在多数据源环境中使用Spring Boot application.yml的mybatis.mapper-locations选项?

我按如下所示设置代码。


这是我的环境。

spring-boot 2.1.2
multi datasource using hikariCp


这是我的应用程序。yml

mybatis:
    mapper-locations: 'classpath:mybatis/test/*.xml'
    type-aliases-package: com.test
    configuration:
      cache-enabled: true
      lazy-loading-enabled: true
      multiple-result-sets-enabled: true
      use-column-label: false
      default-statement-timeout: 65000
      map-underscore-to-camel-case: true

spring.datasource:
  test1:
    driver-class-name: net.sf.log4jdbc.sql.jdbcapi.DriverSpy
    jdbc-url: jdbc:log4jdbc:sqlserver://{SERVER};databaseName={DB NAME};sendStringParametersAsUnicode=false
    username: {USER}
    password: '{PW}'

  test2:
    driver-class-name: net.sf.log4jdbc.sql.jdbcapi.DriverSpy
    jdbc-url: jdbc:log4jdbc:sqlserver://{SERVER};databaseName={DB NAME};sendStringParametersAsUnicode=false
    username: {USER}
    password: '{PW}'


这是spring配置.java文件

@Configuration
public class DataSourceConfig {

    @Bean(name = "test1DataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.test1")
    public DataSource test1DataSource() {
        return DataSourceBuilder.create()
                    //.type(HikariDataSource.class)
                    .build();
    }

    @Bean(name = "sqlTest1SessionFactory")
    public SqlSessionFactory sqlTest1SessionFactory(@Qualifier("test1DataSource") DataSource test1DataSource, ApplicationContext applicationContext) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(test1DataSource);
        //sqlSessionFactoryBean.setConfigLocation(applicationContext.getResource("classpath:config/testConfig.xml"));
        //sqlSessionFactoryBean.setMapperLocations(applicationContext.getResources("classpath:mybatis/test/*.xml"));
        return sqlSessionFactoryBean.getObject();
    }

    @Bean(name = "sqlTest1SessionTemplate")
    public SqlSessionTemplate sqlTest1SessionTemplate(SqlSessionFactory sqlTest1SessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlTest1SessionFactory);
    }
}


有错误代码。

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException: 
### Error querying database.  Cause: java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for com.test.**
### Cause: java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for com.test.**


取消注释('// sqlSessionFactoryBean.setMapperLocations')时,它可以正常工作,因此路径值中没有错别字。

为什么会出现此错误?

0 个答案:

没有答案