简体   繁体   中英

Spring boot application with MySQL connection AND an oracle connection? (Two databases)

I have the following application.properties :

## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url= ${DATASOURCE_URL}
spring.datasource.username= ${DATASOURCE_USERNAME}
spring.datasource.password= ${DATASOURCE_PASSWORD}

## Other Database
second.datasource.url="jdbc:oracle:thin:@localhost:1521:XE"
second.datasource.username=usr
second.datasource.password=password
second.datasource.driver-class-name=oracle.jdbc.OracleDriver
second.jpa.show-sql=true

## Hibernate Properties

# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto = update
spring.jpa.database=default

Goal and things that currently work : The spring datasource at the top works fine. I am able to use that for all of my main needs. The second one, below it, is going to query a legacy system and get data from there.

Problem : I have no idea how to get that second datasource to work at all. I need to get it to perform a query and get it returning something. Ideally I would love to see an example of this that works. I looked at a few blog posts, and googled around, and I am clearly missing some vital information.

the above is default and spring can find it on its own. To create a different DataSource you need to setup a datasource bean somewhere, and read values from a config.

Easiest way would be to create a class with configuration annotation and define beans for both dataSources.

I'd suggest HikariDataSource, you can read more about how to set it up here: https://www.baeldung.com/hikaricp

For configuration you can use Environment by autowiring it and reading your properties from there.

environment.getProperty("second.datasource.url") for example

Check the instructions in this link: https://www.baeldung.com/spring-data-jpa-multiple-databases

1) You need to provide JPA configuration for each of your datasources with 2) independent entity packages for each of these sources and, 3) you must specify one of the data source as Primary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM