0

have an application that runs Spring MVC.

I need it to access 2 different databases in my app (Two Sql servers).

How do I configure this?

Venkady
  • 39
  • 1
  • 1
  • 5

1 Answers1

0

You can access the first database with an EntityManager and use a JdbcTemplate to access the second database

1.application.properties

#SQL Server 1
spring.datasource.url = [url]
spring.datasource.username = [username]
spring.datasource.password = [password]
spring.datasource.driverClassName = [sql Server Driver class name]

#SQl Server 2
spring.secondaryDatasource.url = [url]
spring.secondaryDatasource.username = [username]
spring.secondaryDatasource.password = [password]
spring.secondaryDatasource.driverClassName = [sql Server Driver class name]

2.Create @Configuration class and declare two datasource beans.Create a Jbc template to use to access sql server 2

@Bean
@Primary
@ConfigurationProperties(prefix="spring.datasource")
public DataSource primaryDataSource() {
    return DataSourceBuilder.create().build();
}

@Bean
@ConfigurationProperties(prefix="spring.secondaryDatasource")
public DataSource secondaryDataSource() {
    return DataSourceBuilder.create().build();
}


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

Usage Example

@Repository
public class CustomerRepositoryImpl implements CustomerRepository {


    private final JdbcTemplate jdbcTemplate;

    public CustomerRepositoryImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

}

You can also look at the documentation: https://docs.spring.io/spring-boot/docs/1.2.3.RELEASE/reference/htmlsingle/#howto-use-two-entity-managers

and this site https://www.baeldung.com/spring-data-jpa-multiple-databases

Stephen
  • 169
  • 4
  • 10
  • Hi I have created the application is working I need to access two data base how do I route to primary source(#SQL Server 1) – Venkady Sep 25 '18 at 11:12