1

I have a Entity Class like this

@Entity
@Table(name = "USER")
public class Users {
...
}

During production deployemnt i want to read from this user table. But during Stage Environment deployement i want to read from USER_STAGE table.

@Entity
@Table(name = if (env=='prod') ? "USER" : "USER_STAGE")
public class Users {
...
}

How can i achieve this with out any service level logic?

zamiurratul
  • 201
  • 1
  • 2
  • 12

2 Answers2

1

Consider implementing your own naming strategies to alter table names.

Then expose them as spring beans and integrate with spring boot.

Since the naming strategy could be a bean by itself it could get the configuration parameter of prefix that could be changed depending on the activated profile, env, etc.

I've found this SO thread that talks about naming strategy for "pure hibernate". It also has an example with altered table name.

In addition consider reading this tutorial - it talks about integrating custom naming strategies with spring boot

Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97
0

You should achieve that by seperating your databases.

I recommend you to use different spring profile to handle different database connections, and just setup a local development database e.g. with docker. It should be "a copy" of the production database, means it is in structure similar to it (e.g. the naming of tables, cols and so on is the same).

Best way is to use flyway or liquibase or any other similar tool, to handle versions / migrations of your database.

I have one profile for local development, one for staging and one for production. This way you only have to manage the 'application' file of spring.

phaen
  • 349
  • 2
  • 12
  • Got your point, we have those separation and those are totally different discussion. But, i just want to know whether its possible to assign name of table based on some condition or not? @phaen – zamiurratul Feb 03 '21 at 09:10
  • Alternatively you have a different package for those entities and adjust the entityScan property – Nico Van Belle Feb 03 '21 at 09:14
  • @nico that would lead to code duplication, don't you think? – zamiurratul Feb 03 '21 at 09:18
  • @zamiurratul then, you have to consider the answer Mark Bramnik gave. But tbh I dont see any need for that. Makes everything less complicated and less error prone if you use the same naming strategies for all stages. – phaen Feb 03 '21 at 09:51