Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 views
in Technique[技术] by (71.8m points)

java - Use two datasources with jdbc template

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:

one that has access to the user table for login/register/information update and another for accessing the other tables.

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.

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...