java – Hibernate with multiple databases in the same application

Question:

A system uses a separate database for each client, let's say I will have 500 clients, in this case my database server would have 500 data bases , example:

cliente1 

cliente2 

cliente3

In the configuration of Hibernate, a Factory is generated, which in these configurations contains which bank the system will connect to.

Will there be 500 Factory in the application?

Answer:

We have a similar situation in NHibernate (.NET) due to the architecture of our system, which uses a schema (database) for each branch.

In this case, you can use a SessionFactory only, taking responsibility for creating the connections.

For this you must:

1) Create a class inherited from org.hibernate.connection.DriverConnectionProvider (example in C#):

internal class MeuDbConnectionProvider : DriverConnectionProvider
{
    protected override string ConnectionString {
        // To-Do: Aqui você deve retornar a String de conexão baseada em uma variável
        //        'static' (neste meu caso, chamei de "SessionManager") que provê a base em que vc está conectado no momento
        get { return SessionManager.CurrentDatabaseConnection.ConnectionString; }
    }
    public override System.Data.IDbConnection GetConnection()
    {
        // To-Do: Criar uma nova conexão MySql baseada na String de Conexao
        //        da "base corrente"
        (...)
        return novaConexao;
    }
}

2) Set Hibernate to use your ConnectionProvider for creating connections.

Configuration configuration = new Configuration()
    .setProperty(Environment.CONNECTION_PROVIDER, "com.my.package.MeuDbConnectionProvider");

From then onwards, the power will be in your hands – using just one SessionFactory .

Comments:

  • This situation only applies when you are using the same dialect for all connections;

  • See also this link (in English) .

Scroll to Top