'Spring Boot Connecting to 2 Different Data Sources Using application.properties or application.yaml File
My application using Spring JPA and it should connect to 2 different data sources. One to connect to DB2, the other to connect to Oracle.
I have set my application properties like below:
# DB2 DATA SOURCE
# ==============================
spring.datasource.url=jdbc:db2://server:port/database:currentSchema=schema-name;
spring.datasource.username=user1
spring.datasource.password=password1
spring.datasource.driver-class-name=com.ibm.db2.jcc.DB2Driver
# ORACLE DATA SOURCE
# ==============================
oracle.datasource.url=jdbc:oracle:thin:@server:port/database
oracle.datasource.username=user2
oracle.datasource.password=password2
# ==============================
# = JPA / HIBERNATE
# ==============================
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
# **How to specify the dialects hibernate needs to use in this scenario?**
#spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.DB2390Dialect
#spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
Above, my DB2 is working fine but as soon as I add 2nd data source (for Oracle), I am getting
java.lang.IllegalStateException: Failed to load ApplicationContext Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path ... Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
Solution 1:[1]
Setting properties in application.yml or application.properties don't automatically create DB connections. When using multiple databases you have to configure them manually.
In your case, Spring configures db2 because of spring.datasource.* properties and ignores Oracle DB as it treats them as custom properties. To fix this, you have create separate configuration classes that defines
- Data Source
- Transaction Manager
- Entity Manager Factory
Spring Data team created an example for this.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Pavan Jadda |
