背景
由于需求上需要支持从JDBC的数据源的多个db中读写数据,故而思考是否需要根据db动态创建数据库连接。而项目中常见的数据源配置都是指定db名称的,如下:
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test_db?useUnicode=true&characterEncoding=utf8
username: root
password: root
那SpringBoot数据源是不是真的只能配置一个MySQL的一个db?因此尝试验证SpringBoot是否支持不写死db,而能够在sql中指定。
思考
使用MySQL客户端比如Navicat或者MySQL命令连接MySQL,可以通过dbName.tableName访问所有的db的所有表,比如
select * from testdb.tb1;
而SpringBoot同样是建立与MySQL的TCP连接,那么SpringBoot也应当支持在SQL中指定库名。
验证
1. 配置数据源
spring:
datasource:
url: jdbc:mysql://localhost:3306?useUnicode=true&characterEncoding=utf8
2. 编写mapper
<select id="selectCount" resultType="int">
select count(*) from ${dbName}.${tableName};
</select>
3. 单测
@SpringBootTest
class DataSourceMapperTest {
@Autowired
private DataSourceMapper dataSourceMapper;
@Test
void testSelectCount() {
dataSourceMapper.selectCount("sys", "sys_config");
dataSourceMapper.selectCount("test", "CUSTOMER");
}
}
测试通过,结果表明SpringBoot确实支持在数据源配置中不指定db而在SQL中指定。
总结
开发时很多模板类型的配置常常会让人产生思维定势,从而对开发造成一些障碍,甚至带来额外的开发付负担(比如执行SQL时手动创建连接)。如果你也需要支持访问数据源的多个db,那么你可以在配置数据源的时候不指定db而在SQL中指定。