1. 程式人生 > 實用技巧 >springboot-mybatis配置多資料來源

springboot-mybatis配置多資料來源

第一步,編寫資料來源配置類

@Getter
@Setter
@Configuration
@ConfigurationProperties(prefix = "spring.datasource")
public class DataSourceConfig {

    /**
     * 連線池屬性
     */
    private String type;
    private String driverClassName;
    private String initialSize;
    private String minIdle;
    private String maxActive;
    private String maxWait;
    private String timeBetweenEvictionRunsMillis;
    private String minEvictableIdleTimeMillis;
    private String validationQuery;
    private String testWhileIdle;
    private String testOnBorrow;
    private String testOnReturn;
    private String filters;

    /**
     * 資料來源
     */
    private DataSourceLink configcenter;
    private DataSourceLink basic;

    @Getter
    @Setter
    static class DataSourceLink {
        private String url;
        private String username;
        private String password;
    }

    /**
     * 配置[base]對應資料來源
     */
    @Bean(name = "configCenterDataSource")
    @Primary
    public DataSource configCenterDataSource() {
        return buildDataSource(configcenter, "configCenterDataSource");
    }

    /**
     * 配置[base]對應資料來源
     */
    @Bean(name = "baseDataSource")
    public DataSource baseDataSource() {
        return buildDataSource(basic, "baseDataSource");
    }

    /**
     * 建立資料來源
     *
     * @param dataSourceLink 資料來源連線
     * @param dataSourceName 資料來源標識
     * @return 資料來源
     */
    private AtomikosDataSourceBean buildDataSource(DataSourceLink dataSourceLink, String dataSourceName) {
        Properties prop = new Properties();
        prop.put("url", dataSourceLink.getUrl());
        prop.put("username", dataSourceLink.getUsername());
        prop.put("password", dataSourceLink.getPassword());
        prop.put("driverClassName", driverClassName);
        prop.put("filters", filters);
        prop.put("maxActive", maxActive);
        prop.put("initialSize", initialSize);
        prop.put("maxWait", maxWait);
        prop.put("minIdle", minIdle);
        prop.put("timeBetweenEvictionRunsMillis", timeBetweenEvictionRunsMillis);
        prop.put("minEvictableIdleTimeMillis", minEvictableIdleTimeMillis);
        prop.put("validationQuery", validationQuery);
        prop.put("testWhileIdle", testWhileIdle);
        prop.put("testOnBorrow", testOnBorrow);
        prop.put("testOnReturn", testOnReturn);

        AtomikosDataSourceBean ds = new AtomikosDataSourceBean();
        ds.setXaDataSourceClassName(type);
        ds.setPoolSize(5);
        ds.setXaProperties(prop);
        ds.setUniqueResourceName(dataSourceName);
        ds.setTestQuery("select 1");
        return ds;
    }

}

配置第一個資料來源

@Slf4j
@Configuration
@MapperScan(basePackages = {"com.vanew.trade.erp.batch.web.dao.base"}, sqlSessionTemplateRef = "baseSqlSessionTemplate")
public class BaseSqlSessionTemplateConfig {

//初始化資料來源,從配置檔案中獲取資料來源的引數
    @Value("${vanew.mybatis.base-locations}")
    private String mapperLocations;

    /**
     * 自定義sqlSessionFactory配置(因為沒有用到MybatisAutoConfiguration自動配置類,需要手動配置)
     *
     * @param dataSource 資料來源
     * @return SqlSessionFactory
     * @throws Exception 異常資訊
     */
//獲取mybatis的SqlSessionFactory 
    @Bean
    public SqlSessionFactory baseSqlSessionFactory(@Qualifier("baseDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //如果重寫了 SqlSessionFactory 需要在初始化的時候手動將 mapper 地址 set到 factory 中,否則會報錯:
        //org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)
      
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
        bean.setVfs(SpringBootVFS.class);
        // bean.setPlugins(new MybatisInterceptor());
        bean.setConfigurationProperties(MyBatisProperties.getProperties());
        return bean.getObject();
    }

    /**
     * SqlSessionTemplate 是 SqlSession介面的實現類,是spring-mybatis中的,實現了SqlSession執行緒安全
     *
     * @param sqlSessionFactory sqlSessionFactory
     * @return SqlSessionTemplate
     */
    @Bean
    public SqlSessionTemplate baseSqlSessionTemplate(@Qualifier("baseSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
  **設定mapper檔案存放位置,通過存放位置來區分資料來源**