Search code examples
javaspringhibernatedatasourceproperties-file

Configuring Spring to useMultiple Data Sources


I am trying to connect 2 different schemas within my spring boot application.

To do this I have got 2 different data sources. How should I configure this within my properties files?

I seen this answer which gave me an idea of how to do so. I currently have the following 3 property files in my application:

1. application.properties
2. hibernate.properties
3. multiple-db.properties

application.properties is currently empty. Below are the other 2 files:

hibernate.properties:

# Connection configuration
hibernate.connection.username= my_uname1
hibernate.connection.password= my_pword1

multiple-db.properties:

# Schema 1-Data source configuration
oracle.db.username1= my_uname1
oracle.db.password1= my_pword1
oracle.db.url1= my_url1

# Schema 2-Data source configuration
oracle.db.username2= my_uname2
oracle.db.password1= my_pword2
oracle.db.url2= my_url2

# JPA configuration
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect

# Hibernate configuration
hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
hibernate.connection.driver_class=oracle.jdbc.driver.OracleDriver
hibernate.connection.url=my_url

hibernate.connection.provider_class=org.hibernate.connection.C3P0ConnectionProvider

Is this the correct approach? Do I need 3 properties files, or could I do this all in one?


Solution

  • The Spring documentation suggests a way to create primary and secondary data sources: http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-two-datasources

    Each data source can be configured as described here: http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-configure-a-datasource

    You can access them by using @Autowire from other beans. You can associate a prefix to each data source so you can configure it in your application.properties or application.yml file.

    You can also set one as primary.