如何动态创建数据库并实例化jdbcTemplate?

时间:2018-06-18 09:47:02

标签: java spring postgresql spring-boot spring-jdbc

我接受来自最终用户的数据库名称然后我需要使用Spring jdbcTemplate动态创建并连接到数据库,这样我可以在该数据库中执行DDL / DML语句,所以稍后当用户登录到系统我需要连接到同一个数据库。

我有多个最终用户,需要在登录系统后将它们与各自的数据库连接。

1 个答案:

答案 0 :(得分:0)

答案在这里

以下代码片段对我有用。

// create final Map
private final Map<Long, JdbcTemplate> datasourceFactory = new ConcurrentHashMap<>();

// put JdbcTemplate to the Map
HikariConfig config = new HikariConfig();
Properties p = new Properties();
config.setDataSourceProperties(p);
config.setJdbcUrl(dbUrl);
config.setUsername(username);
config.setPassword(password);
HikariDataSource hds = new HikariDataSource(config);
JdbcTemplate template = new JdbcTemplate(hds);
datasourceFactory.put(someUniqueId, jdbcTemplate);

使用以下代码片段访问 JdbcTemplate,

// Fetch the JdbcTemplate from the Map object
JdbcTemplate jdbcTemplate = datasourceFactory.get(someUniqueId);

这样我们就可以为单个 Spring 应用程序管理多个数据源。