Spring Boot multiple databases, different way - java

First of all sorry for my English.
I need to save information in to different databases, both of them in Oracle SQL developer.
The solutions that I found on internet, all of them are coding in spring, but my project just have a configuration file, where is defined the database, and then how spring knows which database is active, and then is keeping the information there, like magic, I was looking around the internet, and the solution is not working for me...
Maybe you have any idea to how develop this without something like the next:
// Datasource method goes here
#Primary
#Bean(name = "datasource")
#ConfigurationProperties(prefix = "spring.second.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
// LocalContainerEntityManagerFactory goes here
#Primary
#Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(EntityManagerFactoryBuilder builder,
#Qualifier("datasource") DataSource dataSource) {
Map<String, Object> properties = new HashMap<>();
properties.put("hibernate.hbm2ddl.auto", "update");
properties.put("hibernet.dialect","org.hibernate.dialect.MySQL8Dialect");
return builder.dataSource(dataSource).properties(properties).packages("com.example").persistenceUnit("MyEntity").build();
}
I think I have defined the datasource in a properties, but then is doing something different to the datasource method.

I found the solution, that was a different answer of what I'm expected.
I create two Maven Projects, and then in my ConfigRepo by the spring-application-name I tell wich one were consuming what database. And that's all, problem Solved.

Related

Spring Boot Multiple Datasources, specify Datasource on Repository

I´m working on some legacy code, where we have 2 different datasources for our application.
There is one class that defines the configuration for both, and I don't want to separate them into two classes because things will probably break. This is the configuration class
#Configuration
public class DataSourceConfig {
#Bean(name="dataSource")
#Primary
#ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
#Bean(name="merchantsDataSource")
#ConfigurationProperties(prefix = "merchants.datasource")
public DataSource merchantsDataSource() {
return DataSourceBuilder.create().build();
}
}
Being structured this way, I don't think I can use #EnableJpaRepositories as suggested in many places to be able to define Repositories from different Data Sources.
So my question is: is there a way that I can create a Repository for the non-primary Data Source, without having to refactor all legacy code to use new classes?

How can I use different variable names for common Spring Boot Application Properties, when the app never directly calls these variables?

I've created a pretty standard Spring Boot 2.0 app with Services and Repositories to access a database.
I had to set the standard Spring Boot application properties to get it to work, such as:
spring.datasource.url, spring.jpa.database, etc.
However, in order to prevent my properties from overwriting other properties in similar apps hosted in the same place, I need to rename these properties, such as:
myApp.spring.datasource.url, myApp.spring.jpa.database, etc.
Some of these properties will be set by environmental variables instead of the application.properties file.
However, I can't see any way to override those variables in my app.
The standard approach is to use #Value to configure those variables. However, the Spring Boot 2.0 setup for services looks up all these properties "behind the scenes," so that doesn't appear to be an option here.
Is there any way to configure my app to read all those myApp.common.property.name properties and treat them as common.property.name?
Thank you.
Yes, the standard way is to use #Value. But thw work doesn't stop there, you need to create DataSource and EntityManager with these values.
Springboot will create DataSource, Entitymanager and some other components bey looking into default properties(spring.xxx) from the file(hence Spring boot is opinionated). But when you change these names to non default values, then you need to create these components / beans yourself.
Instead of using #Value you could also use #Configurationproperties. #Value also works but you might need to declare like 6 or 7 values with #Value. If you wish to use #ConfigurationProperties, make sure you have #EnableConfigurationProperties annotation added somewhere in your project.
Here is a code snippet. You need to tune it to your project
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(
entityManagerFactoryRef = "entityManagerFactory",
basePackages = { "com.xxx.yyy.repo" }
)
public class SomeDbConfig {
#Primary // Use this if you have multiple datasources or else no use
#Bean(name = "dataSource")
#ConfigurationProperties(prefix = "myApp.spring.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
#Primary
#Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean
entityManagerFactory(
EntityManagerFactoryBuilder builder,
#Qualifier("dataSource") DataSource dataSource
) {
return builder
.dataSource(dataSource)
.packages("com.xxx.yyy.domain")
.persistenceUnit("somename")
.build();
}
#Primary
#Bean(name = "transactionManager")
public PlatformTransactionManager transactionManager(
#Qualifier("entityManagerFactory") EntityManagerFactory
entityManagerFactory
) {
return new JpaTransactionManager(entityManagerFactory);
}
}

Change Spring config connection in runtime

I need to change my connection with the Database in runtime. For Example, if parameter requested is BD1, connect on database 1, if BD2, connect in database 2, etc.
I am using spring boot. What is the best way for this.
I have this #Configuration, but not know to say my repository how to use.
#Configuration
public class DataSourceConfiguration {
#Bean(name = "ccteste")
#ConfigurationProperties("spring.ciclocairu.teste.datasource")
#Primary
public DataSource ciclocairuTeste() {
return DataSourceBuilder.create().build();
}
#Bean(name = "ccprod")
#ConfigurationProperties("spring.ciclocairu.prod.datasource")
public DataSource ciclocairuProd() {
return DataSourceBuilder.create().build();
}
#Bean(name = "tmccteste")
#Autowired
#Primary
DataSourceTransactionManager transactionManagerCicloCairuTeste(#Qualifier("ccteste") DataSource datasource) {
DataSourceTransactionManager txm = new DataSourceTransactionManager(datasource);
return txm;
}
#Bean(name = "tmccprod")
#Autowired
#Primary
DataSourceTransactionManager transactionManagerCicloCairuProd(#Qualifier("ccprod") DataSource datasource) {
DataSourceTransactionManager txm = new DataSourceTransactionManager(datasource);
return txm;
}
}
Looks like you are looking for some data source routing. Spring has AbstractRoutingDataSource for run-time detection what data source should be used.
Abstract DataSource implementation that routes getConnection() calls
to one of various target DataSources based on a lookup key.
Also you can set default datasource by setDefaultTargetDataSource method.
It works in such way: you put data sources that you need in a map in AbstractRoutingDataSource at the bean configuration stage, and when you need to use a specific data source you put the key for this source into the context that linked to the router. This ds-key is linked to the current thread.
Here are examples : Dynamic DataSource Routing with Spring and Spring DataSource Routing
Might take a look at my answer at Manage transactions with multiple datasource, entity managers for same application code
or my blog post: Multi-tenant applications using Spring Boot, JPA, Hibernate and Postgres

Spring Boot doesn't pick spring.datasource.tomcat.* while programmatically configuring datasources?

I am configuring two data sources, and trying to set pooling properties and as per docs I should use spring.datasource.tomcat.*, that doesn't seem to work with the configuration that I am doing. What am I doing wrong? or what am I missing?
My application.properties :
spring.datasource.tomcat.test-on-borrow=true
spring.datasource.tomcat.validationQuery=SELECT 1
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username
spring.datasource.password
spring.read.datasource.tomcat.test-on-borrow=true
spring.read.datasource.tomcat.validationQuery=SELECT 1
spring.read.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.read.datasource.username
spring.read.datasource.password
Below is my configuration class :
I have a similar one for read data source (for different repo/entities)
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactory",
transactionManagerRef = "transactionManager",
basePackages = "com.test.feature.repo.internal")
public class DataSourceConfig {
#Primary
#Bean("dataSource")
#ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource(){
return DataSourceBuilder.create().build();
}
#Primary
#Bean(name="entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
#Qualifier("dataSource")DataSource dataSource){
return builder.dataSource(dataSource).packages("com.test.feature.entity.internal").persistenceUnit("defaultPersistenceUnit").build();
}
#Primary
#Bean(name="transactionManager")
public PlatformTransactionManager transactionManager(#Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory){
return new JpaTransactionManager(entityManagerFactory);
}
}
If I try to use spring.datasource.test-on-borrow=true, then this works.
I really want to know why the .tomcat.* style doesn't work? And what I can I do to make that work?
Even if someone redirects me to some helpful reading material for understanding this, I will be glad. :)
That documentation is about the auto-configuration and you're not using it. If you are writing custom code to setup the DataSource, you are in charge of the binding of the configuration as well.
Your code above has a #ConfigurationPropeties("spring.datasource"). If you remove that, none of the spring.datasource.* properties would be taken into account in your own code.
This section of the doc explains the difference between basic properties (spring.datasource) and data source binding (spring.datasource.xyz.*).
Regardless, if you are creating the DataSource yourself (why?) then use a separate namespace. Reusing the spring.datasource namespace is quite confusing as a user is expecting that the features the auto-configuration provides will be honoured. And they won't since you're writing your own config.
I have added following two lines in my application.properties.
spring.datasource.type=org.apache.tomcat.jdbc.pool.DataSource
spring.read.datasource.type=org.apache.tomcat.jdbc.pool.DataSource
It is working...Thank you.
If you only have one datasource and auto-configuration, you only need to use spring.datasource.* to config. tomcatcp will be selected as a default cp.
In your case: configure two dataSources programmatically , please add the following annotation spring.datasource.type in your application.properties to tell it which connection pool you choose.
spring.datasource.type=org.apache.tomcat.jdbc.pool.DataSource
spring.read.datasource.type=org.apache.tomcat.jdbc.pool.DataSource

Configuring Springboot to work with 2 different databases

I am just learning how to use springboot as a java backend framework and I currently have applications.properties configured to use 1 database.
I am thinking of adding an additional database to store different information instead of saving everything on a single database so I was wondering how (if possible) can i do that?
My application.properties file contains data like this:
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://database:3306...
Any ideas?
You can create two datasources, one bean of them mark as #Primary
#Bean
#ConfigurationProperties(prefix = "datasource.mysql")
public DataSource mysqlDataSource() {
return DataSourceBuilder.create().build();
}
#ConfigurationProperties(prefix = "datasource.postgres")
#Bean
#Primary
public DataSource postgresDataSource() {
return DataSourceBuilder.create().
build();
}
Your application.properties should looks like this:
datasource.mysql.url=jdbc:mysql://localhost:3306/mysql_demo
datasource.mysql.username=root
datasource.mysql.password=root
datasource.mysql.driverClassName=com.mysql.jdbc.Driver
datasource.postgres.url=jdbc:postgresql://localhost:5432/postgres_demo
datasource.postgres.username=postgres
datasource.postgres.password=postgres
datasource.postgres.driverClassName=org.postgresql.Driver

Categories