Is it possible to set up multiple database connections in Dropwizard?

I am working on some code that uses Dropwizard, which will require that I need to connect to at least two different databases (I also plan to use Hibernate). I could not find examples / documentation that would allow me to configure two different database connections in the database block of the .yml configuration file. Is this possible in Dropwizard? If not, what are the workarounds that people have used in the past. Thank you for your help!

+4
source share
1 answer

You can configure multiple databases in the dropwizard. In config.yml, you can have a database configuration like this.

Database1:

driverClass: org.postgresql.Driver
user: user
password: pwd
url: jdbc:postgresql://localhost:5432/db1
validationQuery: select 1
minSize: 2
maxSize: 8

database2:

driverClass: org.postgresql.Driver
user: user
password: pwd
url: jdbc:postgresql://localhost:5432/db2
validationQuery: select 1
minSize: 2
maxSize: 8

And in the configuration class, get both configurations.

public class DBConfig extends Configuration {

    private DatabaseConfiguration database1;
    private DatabaseConfiguration database2;

    public DatabaseConfiguration getDatabase1() {
        return database1;
    }

    public DatabaseConfiguration getDatabase2() {
        return database2;
    }
}

And in your service, configure which Dao to use which database.

@Override
public void run(MyConfiguration configuration,
                Environment environment) throws ClassNotFoundException {
    ... 

    final DBIFactory factory = new DBIFactory();

    // Note that the name parameter when creating the DBIs must be different
    // Otherwise you get an IllegalArgumentException
    final DBI jdbi1 = factory.build(
            environment, configuration.getUserDatabase(), "db1");
    final DBI jdbi2 = factory.build(
            environment, configuration.getItemDatabase(), "db2");

    final MyFirstDAO firstDAO = jdbi1.onDemand(MyFirstDAO.class);
    final MySecondDAO secondDAO = jdbi2.onDemand(MySecondDAO.class);

    ...
}
+10
source

All Articles