JAVA开发之springBoot2.0搭建双数据源

无忌哥哥
풀어 주다: 2018-07-20 11:32:06
원래의
2505명이 탐색했습니다.

最近因为项目需要,需要在程序中同时访问不同的数据库。之前使用springboot注解写代码确实方便快捷,但是如果需要自己需改其中的一些东西来方便自己使用,改起来有点烦,不知道从哪里入手。写个这个记录下。

首先是pom.xml,都是通用的,这里就不贴出来了。

其次就是application.properties配置,笔者因为不同的环境,所以新建了两个application-dev.properties和application-pro.properties配置文件。

 application.properties:指定当前使用那个环境的配置.

spring.profiles.active=dev
로그인 후 복사
application-dev.properties的配置(application-pro.properties类似dev的配置)
로그인 후 복사
#datasource1
spring.datasource.username=**
spring.datasource.password=*****
spring.datasource.jdbc-url=jdbc:mysql://***************
useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#datasource2
spring.datasource.ds1.username=***
spring.datasource.ds1.password=******
spring.datasource.ds1.jdbc-url=jdbc:mysql://***************
useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.ds1.driver-class-name=com.mysql.jdbc.Drive
로그인 후 복사

不同数据源的MyBatis (Config1)

@Configuration
@MapperScan(basePackages = "com.pet.petgame2.mapper.dao", sqlSessionFactoryRef = "petgame2SessionFactory")
public class Config1 {

    @Bean(name = "petgame2")
    @ConfigurationProperties(prefix = "spring.datasource")
    @Primary
    public DataSource dataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "petgame2SessionFactory")
    @Primary
    public SqlSessionFactory sessionFactory(@Qualifier("petgame2") DataSource dataSource) throws Exception{
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:Mapper/pet2Mapper/*.xml"));
        return factoryBean.getObject();
    }

    @Bean(name = "petgame2TransactionManager")
    @Primary
    public DataSourceTransactionManager transactionManager(@Qualifier("petgame2") DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }
}
로그인 후 복사

不同数据源的MyBatis (Config2)

@Configuration
@MapperScan(basePackages = "com.pet.petgame2.mapper.dao2", sqlSessionFactoryRef = "petgamesqlSessionFactory")
public class Config2 {

    @Bean(name = "petgame")
    @ConfigurationProperties(prefix = "spring.datasource.ds1")
    public DataSource dataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "petgamesqlSessionFactory")
    public SqlSessionFactory sessionFactory(@Qualifier("petgame") DataSource dataSource) throws Exception{
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:Mapper/petMapper/*.xml"));
        return factoryBean.getObject();
    }

    @Bean(name = "petgameTransactionManager")
    public DataSourceTransactionManager transactionManager(@Qualifier("petgame") DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }
}
로그인 후 복사

@MapperScan注解会自动扫描mapper的接口文件, factoryBean.setMapperLocations会扫描mapper接口文件对应的Mapper.XML文件,注意这两个的路径不要写错。@Primary设定默认的一个数据库链接配置,必须指定其中一个数据源为默认。

*注意:如果使用了springboot2.0自带的Hikari作为连接池,需要注意properties中的

spring.datasource.url改为spring.datasource.jdbc-url
로그인 후 복사

或者修改config中DataSource为DataSourceProperties,如下

@Bean(name = "petgame2DataSourceProperties")
    @Qualifier("petgame2DataSourceProperties")
    @ConfigurationProperties(prefix = "spring.datasource")
    @Primary
    public DataSourceProperties properties(){
        return new DataSourceProperties();
    }

    @Bean(name = "petgame2")
    @ConfigurationProperties(prefix = "spring.datasource")
    @Primary
    public DataSource dataSource(){
//        return DataSourceBuilder.create().build();
        return properties().initializeDataSourceBuilder().build();
    }
로그인 후 복사

위 내용은 JAVA开发之springBoot2.0搭建双数据源의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!