Use two datasources with jdbc template(通过 jdbc 模板使用两个数据源)
问题描述
所以,我从事过一个 Spring Boot 项目,现在我正在研究数据库.我认为最好为数据库设置两个用户:
So, I've worked on a spring boot project and now I am working on the database. I thought that it would be best to set two users for the database:
一个可以访问用户表以进行 login/register/information
更新,另一个可以访问其他表.
one that has access to the user table for login/register/information
update and another for accessing the other tables.
我的想法是为两个 DataSource 创建两个单独的 bean,每个都有一个单独的用户,当用户想要登录时,控制器会相应地更改 JDBC 模板 DataSource.
My idea was to create two separate beans for two DataSources each with a separate user and when a user wants to log in, the controller would change the JDBCtemplate DataSource accordingly.
但我不确定这是否可行,因为 JDBC 模板已经被定义为 Spring Boot 项目并且我不知道它的范围(我假设如果它不是会话 bean,则更改 DataSource 将适用于所有用户,而不仅仅是一个用户)
But I am not sure if that would work since the JDBCtemplate is already defined as a spring boot project and I don't know it's scope (I assume if it is not a session bean, changing the DataSource would be for all users, not just for one user)
有人知道我应该如何解决这个问题吗?请告诉我!
Does anyone have an idea about how should I tackle this problem? Please let me know!
推荐答案
你可以创建2个JdbcTemplate bean:
You can create 2 JdbcTemplate beans:
// declare
@Bean("jdbc1")
public JdbcTemplate createJdbcTemplate1(@Autowired @Qualifier("datasource1") DataSource dataSource1){
return new JdbcTemplate(dataSource1);
}
@Bean("jdbc2")
public JdbcTemplate createJdbcTemplate2(@Autowired @Qualifier("datasource2") DataSource dataSource2){
return new JdbcTemplate(dataSource2);
}
并在自动装配时指定bean的名称:
and specify name of bean when autowiring:
// use jdbcTemplate1 for login/register/information
@Autowired
@Qualifier("jdbc1")
protected JdbcTemplate jdbcTemplate1;
// use jdbcTemplate2 for other
@Autowired
@Qualifier("jdbc2")
protected JdbcTemplate jdbcTemplate2;
这篇关于通过 jdbc 模板使用两个数据源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:通过 jdbc 模板使用两个数据源


基础教程推荐
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 降序排序:Java Map 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01