简体   繁体   English

具有MySQL连接和oracle连接的Spring Boot应用程序? (两个数据库)

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

I have the following application.properties : 我有以下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. 当前有效的目标和事物:顶部的spring数据源工作正常。 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. 我看了几篇博客文章,然后在Google周围搜索,显然我缺少一些重要信息。

the above is default and spring can find it on its own. 以上是默认设置,spring可以自行找到它。 To create a different DataSource you need to setup a datasource bean somewhere, and read values from a config. 要创建其他数据源,您需要在某处设置数据源bean,并从配置中读取值。

Easiest way would be to create a class with configuration annotation and define beans for both dataSources. 最简单的方法是使用配置注释创建一个类,并为两个数据源定义bean。

I'd suggest HikariDataSource, you can read more about how to set it up here: https://www.baeldung.com/hikaricp 我建议使用HikariDataSource,您可以在此处阅读有关如何进行设置的更多信息: 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 例如environment.getProperty(“ second.datasource.url”)

Check the instructions in this link: https://www.baeldung.com/spring-data-jpa-multiple-databases 查看此链接中的说明: 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. 1)您需要为每个数据源提供JPA配置,并为每个数据源提供2)独立的实体程序包,并且3)您必须将其中一个数据源指定为主数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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