Home > other >  Spring boot jpa entity table name from property file
Spring boot jpa entity table name from property file

Time:01-30

We are working on a spring boot library to generate and validate OTP. It uses database to store the OTP.

We are using Spring Data JPA for Database operations, as it will be easy to handle multiple database systems according to the project.

Now we have ran in to a problem, most of our projects uses Oracle with a single database. When using the the same lib in multiple projects there is a name conflict. So we want the name of the OTP table to be configurable using a property file.

We tried @Table(name = "${otp-table-name}") But its not working.

We did a lots of research and found out the hibernate naming strategy configuration can help.

But we dont want to use lots of configuration in our library as we need the library to be easily usable in the projects.

Can someone help us on this aspect.

Thanks in advance.

CodePudding user response:

You can dynamically determine the actual DataSource based on the current context, use Spring's AbstractRoutingDataSource class. You could write your own version of this class and configure it to use a different data source based on the property file.

This allows you to switch between databases or schema without having to change the code in your library.

See: https://www.baeldung.com/spring-abstract-routing-data-source

CodePudding user response:

Using a NamingStrategy is good approach.

You could let it delegate to an existing NamingStrategy and add a prefix.

Use a library specific default for the prefix, but also allow users of your library specify an alternative prefix.

This way your library can be used without extra configuration, but can also handle the case of multiple applications using it in the same database schema.

Of course this might involve the risk of someone using the default prefix without realizing that, that is already used. It is not clear what the consequences of that scenario are. If the consequences are really bad you should drop the default value and require that a project specific prefix is used. When no prefix is specified throw an exception with an instructional error message telling the user, i.e. the developer how to pick a prefix and where to put it.

  • Related