Hibernate with multiple databases in the same application

3

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

cliente1 

cliente2 

cliente3

In the Hibernate configuration, a Factory is generated where in these configurations it contains which database the system will connect to.

Will there be 500 Factory in the application?

    
asked by anonymous 20.01.2015 / 19:29

1 answer

1

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

In this case, you can only use SessionFactory , assuming the responsibility of creating the connections.

For this, you should:

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 connection creation.

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

From now on, power will be in your hands - using only SessionFactory .

Comments:

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

  • See also this link .

21.01.2015 / 12:45