6

I am connecting to multiple databases in my spring-boot app using Spring Data JPA by determining which database to connect at runtime. How can I check for validation on which database am I actually connected to on which my queries are running?

Kshitij Kohli
  • 4,055
  • 4
  • 19
  • 27
  • Do you use hibernate multitenancy? – Robert Niestroj Dec 17 '19 at 18:41
  • Yes, I am using multiple datasources and following this tutorial : https://javadeveloperzone.com/spring-boot/spring-boot-jpa-multi-tenancy-example/ – Kshitij Kohli Dec 17 '19 at 18:58
  • Which part of this approach do you not trust that you need to validate it? – Robert Niestroj Dec 17 '19 at 19:26
  • On returning the appropriate entity manager, I had a typo and was returning the same entity manager in both cases, hence query running on the same database regardless the input - hence thought arose to validate where I am connecting to. I was able to resolve my actual issue but would still like to explore the possibility of knowing the connection database. – Kshitij Kohli Dec 17 '19 at 19:29

3 Answers3

4

Try to get the URL from the Datasource, maybe will do it:

dataSource.getConnection().getMetaData().getURL();

Checkout DatabaseMetaData documentation for complete details.

hovanessyan
  • 30,580
  • 6
  • 55
  • 83
  • 1
    OP Says he has multiple databases, so he has most likely multiple datasources. To this code the question remains how to get the actually used datasource. – Robert Niestroj Dec 17 '19 at 18:41
0

The referred the Answer from:

how to properly specify database schema in spring boot?

Just appending the schema name after actual DB host name. For my code MYSQL DB is configured, and this worked fine for me:

appname.datasource.url = jdbc:mysql://DBhostname.com/schema_test?useSSL=false

the key name can be any custom name that suits your application

Vishesh
  • 133
  • 3
  • 11
-1

Only thing i can think of is some like a (simplified)

@Entity
public class ConfigDB{
 Integer id;

 String tenant; 
}

then have a repository:

public ConfigDBRepository extends CrudRepository{
  public boolean existsByTenant(String tenant);
}

And the have in every DB this tenant in this table setup for validation.

Robert Niestroj
  • 15,299
  • 14
  • 76
  • 119