RockOrDead
RockOrDead

Reputation: 340

Spring Framework JDBC use two data sources

This is data source conf. file which has tow data sources. I want to use both of them in DAO class but now only the first data source is working. How can i use both of them ? May be they must be setted in the constructor of dao class or reused with getJdbcTemplate()

public class DataSourceConfig {

    // datasource

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("org.postgresql.Driver");
        dataSource.setUrl("jdbc:postgresql://url");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        return dataSource;
    }

    @Bean
    public DataSource dataSourceSecond() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("org.postgresql.Driver");
        dataSource.setUrl("jdbc:postgresql://url");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        return dataSource;
    }

    // set jdbc template

    @Bean
    public JdbcTemplate jdbcTemplate() {
        return new JdbcTemplate(dataSource());
    }

    @Bean
    public JdbcTemplate jdbcTemplateSecond() {
        return new JdbcTemplate(dataSourceSecond());
    }

    // transaction manager

    @Bean
    public DataSourceTransactionManager dataSourceTransactionManager() {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    public TransactionTemplate transactionTemplate() {
        return new TransactionTemplate(dataSourceTransactionManager());
    }

}

dao

@Repository
public class UsersDao extends JdbcDaoSupport {

    @Autowired
    private MessageSourceAccessor msa;

    @Autowired
    public UsersDao(JdbcTemplate jdbcTemplate) {
        setJdbcTemplate(jdbcTemplate);
    }

    public void deleteUser(int userId) {
        String sql = msa.getMessage("sql");
        Object[] args = new Object[] { userId };
        getJdbcTemplate().update(sql, args);
    }

}

Upvotes: 0

Views: 163

Answers (1)

You can do that with using @Qualifier annotation.

Assuming you want to inject both the jdbcTemplates in a particular class

@Repository
public class MyDao extends JdbcDaoSupport {
    @Autowired
    public MyDao(@Qualifier("jdbcTemplate") JdbcTemplate jdbcTemplate, 
            @Qualifier("jdbcTemplateSecond") JdbcTemplate jdbcTemplateSecond) {
     //code 
    }
}

Upvotes: 1

Related Questions