I have an application which uses four databases in different geographical locations. All the databases contains same tables and only the database name is different according to the location. I have to create some reports in my application which uses data from each database. What would be the proper way to create those database connection from a java application and is there a suitable design pattern for this task which I could use?
Connection mysqlCon = DriverManager. getConnection(mysqlUrl, "root", "password"); To connect to multiple databases in a single JDBC program you need to connect to the two (or more) databases simultaneously using the above steps.
Many database management and development tools support multiple connections to homogeneous databases, i.e., where they are all of the same type, ALL MySQL, ALL SQL Server, ALL Oracle, etc. On the other hand, very few support heterogeneous database servers, i.e. MySQL AND SQL Server AND Oracle, etc.
so, based on user login, the application should connect different database server. For Ex: if user "xxx" login with credential and belogs to "ABC" company and the database is "ABC", then ABC data need to display on the web page.
As you have not tagged your question with any of this, hibernate
, JPA
, ORM
, I assume you are dealing with plain JDBC.
Having said that, I suggest you to have a DAO layer to deal with underlying databases, and leave the connection details to specific implementations. You can configure your connection strings in some .properties
files, lets say.
[Complement]
You can also make use of DAO factory, an implementation of Abstract Factory or Factory Method pattern, whichever suits here.
[Links]
There are multiple ways you can achieve this:
Design Patterns:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With