springboot项目连接多个数据库

springboot项目连接多个数据库

1、引入依赖
(在引入依赖的时候注意druid,mybatis,mysql之间版本,如果版本匹配不好可能导致mapper文件为报空指针异常)

   
            org.springframework.boot
            spring-boot-starter
        

        
            mysql
            mysql-connector-java
            runtime
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        

        
            org.springframework.boot
            spring-boot-starter
        

        
            org.mybatis
            mybatis
            3.5.2
        
        
            com.alibaba
            druid
            1.1.12
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            2.1.0
        
        
            redis.clients
            jedis
            3.1.0
        

        
            com.github.pagehelper
            pagehelper
            5.1.10
        
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            com.alibaba
            druid
            1.1.12
        

application.properties 文件配置

server.port=8080
#数据库连接的全局配置
mybatis.configuration.cache-enabled=true
mybatis.configuration.local-cache-scope=session
page.helper.helper-dialect=mysql
page.helper.reasonable=true
page.helper.support-methods-arguments=true


#连接数据库1配置
spring.user.datasourceType=com.alibaba.druid.pool.DruidDataSource
spring.user.datasource.url=jdbc:mysql://127.0.0.1:3306/pingyougou?serverTimezone=UTC
spring.user.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.user.datasource.username=root
spring.user.datasource.password=123
logging.leve.com.yin.databaseproject.dao=debug 

#连接数据库2配置
spring.item.datasourceType=com.alibaba.druid.pool.DruidDataSource
spring.item.datasource.url=jdbc:mysql://127.0.0.1:3306/mybatis?serverTimezone=UTC
spring.item.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.item.datasource.username=root
spring.item.datasource.password=123

2、初始化各个连接数据配置都需要配置基础bean

@Configuration
public class DbCommonConfig {
    @Value("${mybatis.configuration.cache-enabled}")
    private Boolean cacheEnabled;

    @Value("${mybatis.configuration.local-cache-scope}")
    private String localCacheSocpe;

    @Value("${page.helper.helper-dialect}")
    private String helperDialect;

    @Value("${page.helper.reasonable}")
    private String reasonable;

    @Value("${page.helper.support-methods-arguments}")
    private String supportMethodsArguments;

    private static final String LOCAL_CACHE_SCOPE_SESSION = "session";
    private static final String PAGE_PROP_HELPER_DIALECT = "helperDialect";
    private static final String PAGE_PROP_REASONABLE = "reasonable";
    private static final String PAGE_PROP_SUPPORT_METHODS_ARGUMENTS = "supportMethodsArguments";
    private static final String PAGE_PROP_PARAMS = "params";
    private static final String PAGE_HELPER_PARAMS_VALUE = "count=countSql";




    @Bean(name = "mybatisConfig")
    @Scope("prototype")
    public org.apache.ibatis.session.Configuration  mybatisConfig(){
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setCacheEnabled(cacheEnabled);
        if(LOCAL_CACHE_SCOPE_SESSION.equals(localCacheSocpe)){
            configuration.setLocalCacheScope(LocalCacheScope.SESSION);
        }else {
            configuration.setLocalCacheScope(LocalCacheScope.STATEMENT);
        }
        return configuration;
    }

    @Bean
    @Scope("prototype")
    public PageInterceptor pageInterceptor(){
        PageInterceptor pageInterceptor = new PageInterceptor();
        Properties p = new Properties();
        p.setProperty(PAGE_PROP_HELPER_DIALECT, helperDialect);
        p.setProperty(PAGE_PROP_REASONABLE, reasonable);
        p.setProperty(PAGE_PROP_SUPPORT_METHODS_ARGUMENTS, supportMethodsArguments);
        p.setProperty(PAGE_PROP_PARAMS,PAGE_HELPER_PARAMS_VALUE);
        pageInterceptor.setProperties(p);
        return pageInterceptor;
    }

}

3、根据各个数据库的不同情况,设置包的不同地方

@Configuration
@MapperScan(basePackages = DataSqlConfig.PACKAGE,sqlSessionFactoryRef = "DataSqlSessionFactory")
public class DataSqlConfig {
    //mapper文件目录
    static final String PACKAGE = "com.yin.databaseproject.dao.datasql";
    //database驱动器
    @Value("${spring.item.datasourceType}")
    private Class dataSourcceType;
    //mapper文件目录
    private static final String MAPPER_LOCATIONS = "classpath:mapping/datasql/*.xml";

    //处理器包.
    private static final String TYPE_HANDLERS_PACKAGE = "com.yin.handler";
    //暂时不用
    private static final String TYPE_ALIASES_PACKAGE = "com.yin.type";

    @Resource(name = "mybatisConfig")
    private org.apache.ibatis.session.Configuration mybatisConfig;

    @Resource(name = "pageInterceptor")
    private PageInterceptor pageInterceptor;

    @Bean(name = "sqlDataSource")
    @ConfigurationProperties("spring.item.datasource")
    public DataSource sqlDataSource(){
        return DataSourceBuilder.create().type(dataSourcceType).build();
    }

    @Bean(name = "sqlTransactionManager")
    public DataSourceTransactionManager masterTransactionManager(){
        return new DataSourceTransactionManager(sqlDataSource());
    }

    @Bean(name = "DataSqlSessionFactory")
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("sqlDataSource") DataSource sqlDataSource) {
        return SqlSessionFactoryUtil.createSqlSessionFactory(sqlDataSource,TYPE_ALIASES_PACKAGE,
                TYPE_HANDLERS_PACKAGE,MAPPER_LOCATIONS,mybatisConfig,new Interceptor[] {pageInterceptor});
    }

}
@Configuration
@MapperScan(basePackages = DataSourceConfig.PACKAGE,sqlSessionFactoryRef = "druidSqlSessionFactory")
public class DataSourceConfig {
    //mapper文件目录
    static final String PACKAGE = "com.yin.databaseproject.dao.pingyougou";
    //database驱动器
    @Value("${spring.user.datasourceType}")
    private Class dataSourcceType;
    //mapper文件目录
    private static final String MAPPER_LOCATIONS = "classpath:mapping/pingyougou/*.xml";

    //处理器包.
    private static final String TYPE_HANDLERS_PACKAGE = "com.yin.handler";
    //暂时不用
    private static final String TYPE_ALIASES_PACKAGE = "com.yin.type";

    @Resource(name = "mybatisConfig")
    private org.apache.ibatis.session.Configuration mybatisConfig;

    @Resource(name = "pageInterceptor")
    private PageInterceptor pageInterceptor;

    @Bean(name = "masterDataSource")
    @Primary
    @ConfigurationProperties("spring.user.datasource")
    public DataSource masterDataSource(){
        return DataSourceBuilder.create().type(dataSourcceType).build();
    }

    @Bean(name = "masterTransactionManager")
    @Primary
    public DataSourceTransactionManager masterTransactionManager(){
        return new DataSourceTransactionManager(masterDataSource());
    }

    @Bean(name = "druidSqlSessionFactory")
    @Primary
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource masterDataSource) {
        return SqlSessionFactoryUtil.createSqlSessionFactory(masterDataSource,TYPE_ALIASES_PACKAGE,
                TYPE_HANDLERS_PACKAGE,MAPPER_LOCATIONS,mybatisConfig,new Interceptor[] {pageInterceptor});
    }

}

4、构建 sqlSessionFactory 的工具类

public class SqlSessionFactoryUtil {
    public static SqlSessionFactory createSqlSessionFactory(DataSource dataSource, final String typeAliasesPackage,
                                                            final String typeHandlersPackage, final String mapperLocations,
                                                            final Configuration mybatisConfig, Interceptor[] plugins){
        try {
            SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
            sqlSessionFactoryBean.setDataSource(dataSource);
            sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);
            sqlSessionFactoryBean.setTypeHandlersPackage(typeHandlersPackage);
            sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
            sqlSessionFactoryBean.setConfiguration(mybatisConfig);
            sqlSessionFactoryBean.setPlugins(plugins);
            return sqlSessionFactoryBean.getObject();
        } catch (IOException e) {
            return null;
        } catch (Exception e) {
            return null;
        }
        
    }
}

附上项目目录结构
github地址:https://github.com/fajingyin/sprringboot_double_database.git
springboot项目连接多个数据库_第1张图片

你可能感兴趣的:(springboot)