Utku Özdemir
Utku Özdemir

Reputation: 7725

HikariCP - Setting connected database dynamically on connection check-in and check-out from connection pool

I need to switch the database when a connection is checked-in and checked-out from pool. For instance, session X needs to receive a connection to database A and session Y needs to receive connection to database B.

I amd able to do it with C3P0 using a connection customizer. It calls the methods onCheckIn and onCheckOut of AbstractConnectionCustomizer, so I can do something like:

public class MyConnectionCustomizer extends AbstractConnectionCustomizer {
    @Override
    public void onCheckOut(Connection c, String parentDataSourceIdentityToken) throws Exception {
        if (something) {
            c.setCatalog("some database name");
        }
    }

    @Override
    public void onCheckIn(Connection c, String parentDataSourceIdentityToken) throws Exception {
        c.setCatalog("some other database name");
    }
}

I am trying to switch to HikariCP but it calls the customize method of the IConnectionCustomizer only once, when the connection gets created. So, how can I manage to implement such functionality?

Upvotes: 2

Views: 3416

Answers (2)

krishna
krishna

Reputation: 41

One use case is multi-tenancy where there is single Database with multiple schemas. Based on the tenant logged into the application we need to switch the schema dynamically

Upvotes: 4

brettw
brettw

Reputation: 11114

I'm trying to understand the use-case for this? Why wouldn't you use separate pools, if session X really needs a connection to database A, and session Y needs a connection to database B?

HikariCP will likely never support such functionality (I can say that as one of the authors). A connection pool should provide a DataSource that is completely transparent to the application, such that if the pool was removed and the native DataSource was used instead the application would function identically (albeit less efficiently).

The very fact that you can do something like this in C3P0, but not in HikariCP, Vibur, or Apache DBCP should be a red-flag. Using such functionality locks you into a specific pool implementation, which is never a good thing.

Sorry, I can't provide a happy answer. If I were you I would consider writing an application level helper class to get/return connections that provides the semantics you are looking for.

Upvotes: 2

Related Questions