工作上遇到一个需求,需要从系统外部的一个数据库读取数据,记录一下配置过程.
更新了代码,上个版本的有问题,无法加载data source 😞
项目信息
Springboot 2.1.6.RELEASE
Jooq 5.0.2
Flyway 6.5.5
Gradle 6.4.1
需求分析
因为外部数据库只需要读取3张表,决定使用mybatis连接外部数据库.
配置步骤
-
添加mybatis,dbcp2依赖,dbcp2可以不使用.
implementation group: 'org.mybatis.spring.boot', name: 'mybatis-spring-boot-starter', version: '2.1.4' implementation group: 'org.apache.commons', name: 'commons-dbcp2', version: '2.8.0'
-
添加外部数据库信息
数据库连接要是用jdbc-url, 在使用多数据源的时候需要使用jdbc-url.spring: datasource: // 项目使用数据库 jdbc-url: jdbc:postgresql://ip:port/db_name username: name password: password extra: // 外部数据库 jdbc-url: jdbc:postgresql://ip:port/db_name username: name password: password flyway: // 为了autoconfig flyway增加flyway数据库配置 url: jdbc:postgresql://ip:port/db_name user: name password: password out-of-order: true
-
添加配置类
@Configuration(proxyBeanMethods = false) @MapperScan(basePackages = {"com.lenovo.pb.mapper.extra"},sqlSessionFactoryRef = "sqlSessionFactoryExtra") @Data public class DataSourceConfig { @Bean @Primary @ConfigurationProperties("spring.datasource") public DataSourceProperties firstDataSourceProperties() { return new DataSourceProperties(); } @Bean @Primary public HikariDataSource firstDataSource(DataSourceProperties firstDataSourceProperties) { // type可以不指定,springboot默认会使用HikariDataSource return firstDataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build(); } @Bean @ConfigurationProperties("spring.extra") public DataSourceProperties extraDataSourceProperties() { return new DataSourceProperties(); } @Bean public BasicDataSource extraDataSource( @Qualifier("extraDataSourceProperties") DataSourceProperties extraDataSourceProperties) { // type可以不指定,springboot默认会使用HikariDataSource return extraDataSourceProperties.initializeDataSourceBuilder().type(BasicDataSource.class).build(); } @Bean(name = "sqlSessionFactoryExtra") public SqlSessionFactory sqlSessionFactoryExtra(@Qualifier("extraDataSource") DataSource extraDataSource) throws Exception { SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setDataSource(extraDataSource); Objects.requireNonNull(factoryBean.getObject()).getConfiguration().setMapUnderscoreToCamelCase(true); return factoryBean.getObject(); } @Bean public SqlSessionTemplate sqlSessionTemplateExtra(@Qualifier("extraDataSource") DataSource extraDataSource) throws Exception { return new SqlSessionTemplate(sqlSessionFactoryExtra(extraDataSource)); }
}
```
- 添加mapper接口
mapper需要放在配置类中指定的basePackages中@Mapper public interface IncidentMapper { @Select("SELECT * from table_name") List<IncidentEntry> findAll(); }
搞定,接下来在需要的地方注入mapper使用.