Last Updated on 10 August 2019   |   Print Email
In this Hibernate tutorial, I will share with you how to write code that changes database (or schema) dynamically at runtime for a Java application that uses Hibernate framework. Sometimes you have to develop an application that work with multiple databases and it allows the users to switch among different databases smoothly, without restarting the application.You know, we usually use Hibernate with a fixed database whose connection information is specified via hibernate.cfg.xml file. To allow changing database dynamically at runtime, we need to use programmatic configuration for Hibernate. For example, the following code snippet illustrates how to create a SessionFactory from a Configuration object:
As you can see, the database connection information is set in programmatic way – not fixed in XML file – so we can base on that to change database at runtime. So based on that Hibernate programmatic configuration, code a utility method that opens a SessionFactory based on the database name provided, as follows:
// get selected database name from the user:
String databaseName = …
SessionFactory sessionFactory = HibernateUtil.getSessionFactory(databaseName);
Session session = sessionFactory.openSession();
// work with session...
session.close();
sessionFactory.close();
The names of databases on the server may not be fixed or not known at runtime, so code the second utility method that lists all names of databases on the server as follows:
Here, we use pure JDBC code to get the names of databases on the server, filtered by the String parameter filter so we can get only relevant database names.Put the above methods in a utility class called HibernateUtil.And now I will show you an example Java Swing program that allows the user to read data from different databases. The program looks like this:
As you can see, upon startup the program presents some database names in a dropdown list. The user can choose one database and click the Get Data button to read the data from that database into the table underneath. For example, getting data from the bookstoredbdatabase:Suppose that all databases have same table structure.For your reference, below I list code of the relevant Java classes.Code of the main Java Swing program:
That’s how to write code to change database dynamically at runtime with Hibernate framework. Based on this tutorial, you can also implement the same functionality for Java web applications.
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
Could you please post a spring-hibernate dynamic connection to the DB example? The DB name is passed as a parameter or from a table with a different DB connection anyway.
Comments