Search code examples
postgresqlhibernateormmultiple-databases

How to handle multiple database by hibernate without multiple cfg.xml files


We have a Java-Hibernate based web application in which we deal with PostgreSQL database.(It is a single database having multiple schema(s) in it.)

Currently we are facing scalability issues so we have decided to split our schema(s) among multiple database.

Example:

  • Previously we have database called "mydb".
  • And now we split database like "mydb_1", "mydb_2", "mydb_3", so on... (As load will increase, we will create new database.)

Problem:

  • How to manage multiple database from one *.cfg.xml? (We do not want to introduce multiple *.cfg.xml (for every database) every time.)
  • Can this be achieved with newer hibernate version? (We are ready to upgrade our Hibernate version)
  • Do we need to create pool of session factory? (I think its a bad idea and thought... :) )

Note: It would be great, if anyone can provide tutorial/document link for this.

Similar Question: Hibernate using multiple databases

(I am expecting similar kind of answer but without multiple cfg.xml :( )


Solution

  • Ok, so your requirement is not

    only one hibernate config file

    but to be able to

    create new sessionFactory without stopping the server.

    The code in the question you referenced is looking like :

    Configuration config = new Configuration().configure("<complete path to your cfg.xml file>");
    SessionFactory sessionFactory = config.buildSessionFactory();
    

    AS you can see you have a config object first, before getting a sessionFactory. Just fiddle with it in the code before buiding the session factory :

    Configuration config = new Configuration().configure("<complete path to your cfg.xml file>");
    config.setProperty("datasource", new_datasource_to_the_new_database)
    SessionFactory sessionFactory = config.buildSessionFactory();
    
    • replace the "datasource" key by the actual key you are using in the current hibernate.cfg.xml file so that is overrides it. Build new data source, the same way you are building it currently, pointing to the new database.
    • keep the session factory in an accessible location
    • When doing treatment, choose the the right sessionFactory and get a session from there.