最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

springboot mybatis調(diào)用多個數(shù)據(jù)源引發(fā)的錯誤問題

 更新時間:2022年01月14日 10:23:56   作者:如是雨林  
這篇文章主要介紹了springboot mybatis調(diào)用多個數(shù)據(jù)源引發(fā)的錯誤問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

springboot mybatis調(diào)用多個數(shù)據(jù)源錯誤

報錯

'org.springframework.boot.autoconfigure.jdbc.DataSourceInitializerInvoker': Invocation of init method failed; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'javax.sql.DataSource' available: more than one 'primary' bean found among candidates: [mssqlDataSource, postgreDataSource]

從后往前復制的,加粗的是重點。

因為有多個數(shù)據(jù)源使用同一個mapper接口,但是都用@Primary,則會引起此錯誤。

如圖所示:

從上面兩圖可以看出都用了同一個mapper接口,都添加了@Primary。

解決方法

解決方法有兩種,一種是把其中一個數(shù)據(jù)源去掉@Primary,動態(tài)調(diào)用數(shù)據(jù)源,就是需要代碼切換使用的數(shù)據(jù)源。

如果要同時使用兩個數(shù)據(jù)源,那就用不同的mapper,相當于postgre用postgre部分的mapper,sqlserver用sqlserver部分的mapper,大家互不干擾,就算@primary也沒事

如圖所示,我將postgre的MapperScan改了

springboot-mybatis多數(shù)據(jù)源及踩坑

springboot項目結(jié)構如下

springboot配置文件內(nèi)容如下

動態(tài)數(shù)據(jù)源的配置類如下

(必須保證能被ComponentScan掃描到):

package com.letzgo.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author allen
 * @date 2019-01-10 15:08
 */
public class DynamicDatasourceConfig {

    @Configuration
    @MapperScan(basePackages = "com.letzgo.dao.master")
    public static class Master {
        @Primary
        @Bean("masterDataSource")
        @Qualifier("masterDataSource")
        @ConfigurationProperties(prefix = "spring.datasource.master")
        public DataSource dataSource() {
            return new DruidDataSource();
        }

        @Primary
        @Bean("masterSqlSessionFactory")
        @Qualifier("masterSqlSessionFactory")
        public SqlSessionFactory sqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource) throws Exception {
            SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
            factoryBean.setDataSource(dataSource);
            factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/master/*.xml"));
            return factoryBean.getObject();
        }

        @Primary
        @Bean("masterTransactionManager")
        @Qualifier("masterTransactionManager")
        public DataSourceTransactionManager transactionManager(@Qualifier("masterDataSource") DataSource dataSource) {
            return new DataSourceTransactionManager(dataSource);
        }

        @Primary
        @Bean("masterSqlSessionTemplate")
        @Qualifier("masterSqlSessionTemplate")
        public SqlSessionTemplate sqlSessionTemplate(@Qualifier("masterSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
            return new SqlSessionTemplate(sqlSessionFactory);
        }

    }

    @Configuration
    @MapperScan(basePackages = "com.letzgo.dao.slave")
    public static class Slave {
        @Bean("slaveDataSource")
        @Qualifier("slaveDataSource")
        @ConfigurationProperties(prefix = "spring.datasource.slave")
        public DataSource dataSource() {
            return new DruidDataSource();
        }

        @Bean("slaveSqlSessionFactory")
        @Qualifier("slaveSqlSessionFactory")
        public SqlSessionFactory sqlSessionFactory(@Qualifier("slaveDataSource") DataSource dataSource) throws Exception {
            SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
            factoryBean.setDataSource(dataSource);
            factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/slave/*.xml"));
            return factoryBean.getObject();
        }

        @Bean("slaveTransactionManager")
        @Qualifier("slaveTransactionManager")
        public DataSourceTransactionManager transactionManager(@Qualifier("slaveDataSource") DataSource dataSource) {
            return new DataSourceTransactionManager(dataSource);
        }

        @Bean("slaveSqlSessionTemplate")
        @Qualifier("slaveSqlSessionTemplate")
        public SqlSessionTemplate sqlSessionTemplate(@Qualifier("slaveSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
            return new SqlSessionTemplate(sqlSessionFactory);
        }
    }

}

完成基本配置之后,分別在master和slave中寫一個數(shù)據(jù)庫訪問操作,再開放兩個簡單的接口,分別觸發(fā)master和slave的數(shù)據(jù)看訪問操作。

至此沒項目基本結(jié)構搭建已完成,啟動項目,進行測試。

我們會發(fā)現(xiàn)這樣master的數(shù)據(jù)庫訪問是能正常訪問的,但是slave的數(shù)據(jù)庫操作是不行的,報錯信息如下:

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

對于這樣錯誤,起初企圖通過百度解決,大部分都是說xml文件的命名空間和dao接口全名不對應或者說是接口方法和xml中的方法不對應等等解決方法,

本人檢查了自己的代碼多遍重啟多遍均無法解決,并不是說這些方法不對,但是本案例的問題卻不是這些問題導致的。最后無奈,只能硬著頭皮去看源碼,最后發(fā)現(xiàn)了問題所在。

debug源碼調(diào)試到最后,發(fā)現(xiàn)不論是執(zhí)行mater還是slave的數(shù)據(jù)庫操作,使用了相同的SqlSession,同一個!??!這個肯定是有問題的。

繼續(xù)看源碼進行查,看SqlSession的注入過程。

我們知道m(xù)ybatis只要寫接口不用寫實現(xiàn)類(應該是3.0之后的版本),實際上是使用了代理,每個dao接口,在spring容器中其實是對應一個MapperFactoryBean(不懂FactoryBean的可以去多看看spring的一些核心接口,要想看懂spring源碼必須要知道的)。

當從容器中獲取bean的時候,MapperFactoryBean的getObject方法就會根據(jù)SqlSession實例生產(chǎn)一個MapperProxy對象的代理類。

問題的關鍵就在于MapperFactoryBean,他繼承了SqlSessionDaoSupport類,他有一個屬性,就是SqlSession,而且剛才所說的創(chuàng)建代理類所依賴的SqlSession實例就是這個。那我們看這個SqlSession實例是什么時候注入的就可以了,就能找到為什么注入了同一個對象了。

找spring注入的地方,spring注入的方式個人目前知道的有注解處理器如@Autowired的注解處理器AutowiredAnnotationBeanPostProcessor等類似的BeanPostProcessor接口的實現(xiàn)類,還有一種就是在BeanDefinition中定義器屬性的注入方式,在bean的定義階段就決定了的,前者如果不知道的可以看看,在此不做贅述,后者的處理過程源碼如下(只截取核心部分,感興趣的可以自己看一下處理過程,調(diào)用鏈比較深,貼代碼會比較多,看著眼花繚亂):

debug到dao接口類的的BeanDefinition(上文已說過其實是MapperFactoryBean),發(fā)現(xiàn)他的autowiremode是2,參照源碼

即可發(fā)現(xiàn)為按照類型自動裝配

最關鍵的來了

debug的時候發(fā)現(xiàn),master的dao接口執(zhí)行到this.autowireByType(beanName, mbd, bw, newPvs)方法中,給MapperFactoryBean中SqlSession屬性注入的實例是masterSqlSessionTemplate對象,

slave的dao接口執(zhí)行該方法時注入的也是masterSqlSessionTemplate對象,按類型注入,spring容器中找到一個即注入(此時slaveSqlSessionTemplate也在容器中,為什么按類型注入找到了masterSqlSessionTemplate卻沒報錯,應該是@Primary的作用)

至此,問題產(chǎn)生的原因已基本找到,那該如何解決呢?BeanDefinition為什么會定義成autowiremode=2呢,只能找@MapperScan看了,看這個注解的處理源碼,最后找到ClassPathMapperScanner以下方法:

private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) {
        Iterator var3 = beanDefinitions.iterator();

        while(var3.hasNext()) {
            BeanDefinitionHolder holder = (BeanDefinitionHolder)var3.next();
            GenericBeanDefinition definition = (GenericBeanDefinition)holder.getBeanDefinition();
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Creating MapperFactoryBean with name '" + holder.getBeanName() + "' and '" + definition.getBeanClassName() + "' mapperInterface");
            }

            definition.getConstructorArgumentValues().addGenericArgumentValue(definition.getBeanClassName());
            definition.setBeanClass(this.mapperFactoryBean.getClass());
            definition.getPropertyValues().add("addToConfig", this.addToConfig);
            boolean explicitFactoryUsed = false;
            if (StringUtils.hasText(this.sqlSessionFactoryBeanName)) {
                definition.getPropertyValues().add("sqlSessionFactory", new RuntimeBeanReference(this.sqlSessionFactoryBeanName));
                explicitFactoryUsed = true;
            } else if (this.sqlSessionFactory != null) {
                definition.getPropertyValues().add("sqlSessionFactory", this.sqlSessionFactory);
                explicitFactoryUsed = true;
            }

            if (StringUtils.hasText(this.sqlSessionTemplateBeanName)) {
                if (explicitFactoryUsed) {
                    this.logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
                }

                definition.getPropertyValues().add("sqlSessionTemplate", new RuntimeBeanReference(this.sqlSessionTemplateBeanName));
                explicitFactoryUsed = true;
            } else if (this.sqlSessionTemplate != null) {
                if (explicitFactoryUsed) {
                    this.logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
                }

                definition.getPropertyValues().add("sqlSessionTemplate", this.sqlSessionTemplate);
                explicitFactoryUsed = true;
            }

            if (!explicitFactoryUsed) {
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("Enabling autowire by type for MapperFactoryBean with name '" + holder.getBeanName() + "'.");
                }

                definition.setAutowireMode(2);
            }
        }

    }

44行是關鍵,但是有個條件,這個條件成立的原因就是@MapperScan注解沒有指定過sqlSessionTemplateRef或者sqlSessionFactoryRef,正因為沒有指定特定的sqlSessionTemplate或者sqlSessionFactory,mybatis默認采用按類型自動裝配的方式進行注入。

至此,問題解決方案已出:

代碼中的兩個@MapperScan用法分別改為:

@MapperScan(basePackages = "com.letzgo.dao.master", sqlSessionFactoryRef = "masterSqlSessionFactory", sqlSessionTemplateRef = "masterSqlSessionTemplate")??
@MapperScan(basePackages = "com.letzgo.dao.slave", sqlSessionFactoryRef = "slaveSqlSessionFactory", sqlSessionTemplateRef = "slaveSqlSessionTemplate")

重啟進行測試,問題解決。

PS:

還是對各種注解使用方法不了解(或者說對框架的源碼不了解),導致搞了這么久的問題,還好最后查到了,記錄于此,給自己加深印象,以后還是要多看源碼。以上僅為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

  • Spring?Boot如何通過Actuator顯示git和build的信息

    Spring?Boot如何通過Actuator顯示git和build的信息

    這篇文章主要介紹了Spring?Boot通過Actuator顯示git和build的信息,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-01-01
  • Spring?Security中的CORS詳解

    Spring?Security中的CORS詳解

    CORS(Cross-Origin?Resource?Sharing)是一種允許不同源之間進行資源共享的W3C標準,它通過在服務器端設置特定的HTTP響應頭,實現(xiàn)了跨域請求的功能,這種機制要求瀏覽器和服務器的支持,本文給大家介紹Spring?Security中的CORS,感興趣的朋友一起看看吧
    2024-10-10
  • Java中indexOf函數(shù)示例詳解

    Java中indexOf函數(shù)示例詳解

    Java String 類的 indexOf() 方法返回指定字符串中指定字符或字符串第一次出現(xiàn)的位置,這篇文章主要介紹了Java中indexOf函數(shù)詳解,需要的朋友可以參考下
    2024-01-01
  • Java實現(xiàn)快速冪算法詳解

    Java實現(xiàn)快速冪算法詳解

    快速冪是用來解決求冪運算的高效方式。此算法偶爾會出現(xiàn)在筆試以及面試中,特意花時間研究了下這題,感興趣的小伙伴快跟隨小編一起學習一下
    2022-10-10
  • Java實現(xiàn)幾種序列化方式總結(jié)

    Java實現(xiàn)幾種序列化方式總結(jié)

    本篇文章主要介紹了Java實現(xiàn)幾種序列化方式總結(jié),包括Java原生以流的方法進行的序列化、Json序列化、FastJson序列化、Protobuff序列化,有興趣的可以了解一下,
    2017-03-03
  • log4j2使用filter過濾日志方式

    log4j2使用filter過濾日志方式

    這篇文章主要介紹了log4j2使用filter過濾日志方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • Java中遍歷集合的并發(fā)修改異常解決方案實例代碼

    Java中遍歷集合的并發(fā)修改異常解決方案實例代碼

    當你遍歷集合的同時,又往集合中添加或者刪除元素,就可能報并發(fā)修改異常,下面這篇文章主要給大家介紹了關于Java中遍歷集合的并發(fā)修改異常解決方案的相關資料,需要的朋友可以參考下
    2022-12-12
  • HttpClient 請求 URL字符集轉(zhuǎn)碼問題

    HttpClient 請求 URL字符集轉(zhuǎn)碼問題

    這篇文章主要介紹了HttpClient 請求 URL字符集轉(zhuǎn)碼問題,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-01-01
  • spring cloud 之 Feign 使用HTTP請求遠程服務的實現(xiàn)方法

    spring cloud 之 Feign 使用HTTP請求遠程服務的實現(xiàn)方法

    下面小編就為大家?guī)硪黄猻pring cloud 之 Feign 使用HTTP請求遠程服務的實現(xiàn)方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-06-06
  • IDEA+Maven打JAR包的兩種方法步驟詳解

    IDEA+Maven打JAR包的兩種方法步驟詳解

    Idea中為一般的非Web項目打Jar包是有自己的方法的,下面這篇文章主要給大家介紹了關于IDEA+Maven打JAR包的兩種方法,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
    2022-09-09

最新評論

泰和县| 中牟县| 定陶县| 桂阳县| 梓潼县| 潞城市| 思南县| 梨树县| 南召县| 武山县| 静安区| 团风县| 准格尔旗| 武功县| 浮山县| 聊城市| 专栏| 崇州市| 沧州市| 梅河口市| 平谷区| 河津市| 宜兴市| 砀山县| 上高县| 长泰县| 遂平县| 长垣县| 祁连县| 高雄县| 深水埗区| 瑞安市| 光山县| 浮梁县| 大庆市| 瑞昌市| 临江市| 东丽区| 申扎县| 青川县| 宝清县|