海南做網站的google chrome
在上一篇:《【已解決】Spring Boot多數據源的時候,mybatis報錯提示:Invalid bound statement (not found)》?凱哥(凱哥Java)?已經接受了,在Spring Boot配置多數據源時候,因為自己馬虎,導致的一個坑。下面,凱哥在介紹配置多數據源時候的坑:
模仿另一個項目的配置,但第二個數據源一直報異常:
查資料后,始終認為是配置的mapper.xml和dao的問題。但無論怎么改,都不行。
最后發(fā)現之前那個項目,第二個數據源對應的dao,都沒有加@Mapper注解,遂去掉后即正常了。(可能和我將第一個數據源配置成Primary有關系?)
暫不清楚具體原因,僅此記錄。
------------- 后記?-------------?
經測試,果然是因為@Primary注解引起的。引起問題注解的代碼如下:
@Configuration
@MapperScan(basePackages = "com.kaigejava.trade.admin.dao", sqlSessionFactoryRef = "defaultSqlSessionFactory")
public class TradeSystemConfig {
? ? /**
? ? ?* Bean 將這個對象放入Spring容器中
? ? ?* Primary 表示這個數據源是默認數據源
? ? ?* ConfigurationProperties 讀取application.properties中的配置參數映射成為一個對象
? ? ?* prefix 表示參數的前綴
? ? ?*
? ? ?* @return {@link DataSource}
? ? ?*/
? ? @Bean(name = "defaultDataSource")
? ??@Primary
? ? @ConfigurationProperties(prefix = "spring.datasource.tts")
? ? public DataSource getDateSourceTts() {
? ? ? ? return DataSourceBuilder.create().build();
? ? }
? ? /**
? ? ?* 表示這個數據源是默認數據源
? ? ?* Qualifier 表示查找Spring容器中名字為defaultDataSource的對象
? ? ?*
? ? ?* @param datasource {@link DataSource}
? ? ?* @return @{link SqlSessionFactory}
? ? ?* @throws Exception ex
? ? ?*/
? ? @Bean(name = "defaultSqlSessionFactory")
? ??@Primary
? ? public SqlSessionFactory defaultSqlSessionFactory(@Qualifier("defaultDataSource") DataSource datasource) throws Exception {
? ? ? ? SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
? ? ? ? org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
? ? ? ? configuration.setMapUnderscoreToCamelCase(true);
? ? ? ? bean.setConfiguration(configuration);
? ? ? ? bean.setDataSource(datasource);
? ? ? ? // 設置mybatis的xml所在位置
? ? ? ? bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
? ? ? ? return bean.getObject();
? ? }
? ? /**
? ? ?* 表示這個數據源是默認數據源
? ? ?*
? ? ?* @param sessionFactory {@link SqlSessionFactory}
? ? ?* @return {@link SqlSessionTemplate}
? ? ?*/
? ? @Bean("defaultSqlSessionTemplate")
? ??@Primary
? ? public SqlSessionTemplate defaultSqlSessionTemplate(
? ? ? ? ? ? @Qualifier("defaultSqlSessionFactory") SqlSessionFactory sessionFactory) {
? ? ? ? return new SqlSessionTemplate(sessionFactory);
? ? }
}
可以去掉這個注解,然后Dao便可以正常寫上@Mapper注解了。