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, assuming the responsibility to create the connections.
For that, you must:
1) Create an inherited class 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 then on, power will be in your hands - using only one SessionFactory
.
Remarks:
You want to know if you’re gonna keep 500 instacing of Entitymanagerfactory?
– Caffé
I’m using only Hibernate and not JPA, in the same application I want to connect say the 500 mysql database, I wanted to know if it had how to create only a Factory and from that I connect to 500 database
– Rodrigo Rodrigues
I would not like to create a Factory for each connection to the database, this will detonate the server memory!
– Rodrigo Rodrigues
Consider showing your code (Hibernate setting for more than one database and session creation). Tip: You can create the contexts of on-demand data access and destroy when inactive, so you’ll only have 500 contexts if all customers access it at the same time. If the 500 simultaneously connected clients do not compensate for the infrastructure investment, you can reconsider your database architecture (other than per client separation and other types of non-relational databases).
– Caffé
So we can conclude that we can not only have a Factory and use it for several databases, but for each database I will have to give a Factory = config.buildSessionFactory(); ie, it is totally unfeasible in my case, remembering that can have more than 500 clients!
– Rodrigo Rodrigues
If when you say "Factory" you mean "Sessionfactory," yes, it is one for each database. Sessionfactory maintains a connection pool for a given database. You can measure to know in advance how much memory and other infrared resources you will need. 500 Databases or 500 simultaneous connections on an SQL server can cost more than 500 instances of Sessionfactory.
– Caffé
Blz Caffe, then I’ll do a simulation and anything put the result here, valeww
– Rodrigo Rodrigues