Change @Table name value on runtime in Hibernate

Change @Table name value on runtime in Hibernate

There are scenarios that an application needs to access multiple databases with different table names but with the same table structures. One way is to create separate entities, repositories for each connection. But it causes code duplication, and in the end, the code becomes difficult to maintain. Another approach is to override table names at the runtime in Hibernate. In this article, we discuss how to change the @Table name value on runtime in Hibernate.

Limitations

Before jumping to the implementation, it’s crucial to know the limitation. Table names can be changed/overridden only at the application start-up time. Not while the application is running. Maybe there’s a way to achieve that, but Hibernate doesn’t support it.

Additionally, the assumption is that you use either Hibernate directly or via Spring/Spring Boot Data JPA. It should work in both cases.

Override Entity @Table names

First, we must create an XML file under the resources directory to provide alternative table names. Let’s call it orm.xml.

Then we create a data source configuration file and load the orm.xml file based on a condition (profile name in this case). For that, create a config file as below,

The values of JDBC URL, username, and password can be loaded from the application.yml file. You can learn more about it here.

If you have more than one mapping, create multiple .xml files and put them in the resources directory. However, with a single database connection, you can only load one of them at a time.

Although the criteria to load orm.xml is based on the profile, you can change that condition according to your needs.

As we have stated earlier, to change the @Table name value/mapping on runtime in Hibernate, you must restart the application.

Inline/featured images credits