0

I am new to Springboot and trying to build a small rest-service. We have a DB deployed on different environments (e.g. DEV, TEST). The rest-service will make a call to the appropriate database based on the received query param (e.g. ?env=TEST). The schemas of the deployed database are the same, the difference is only in connection string. I have some questions related to this task.

I read a few articles how to work with multiple databases using Spring JPA (for example this one: https://www.baeldung.com/spring-data-jpa-multiple-databases). It did work, but in the given example they get different entites from different databases using different queries, in my case the entity and the query is the same, but I still have to duplicate repositories, transactionManagers, entityManagers etc because of different datasources. And this is just two environments and I have more of them. I have another thought that I might need to recreate the repository each time I process a request (to make the repository non-singleton). I am not sure if it is a good practice.

Maybe it worth to use JDBCTemplate instead of Spring JPA in this case? Could you please suggest something how to approach such a task?

jazzyekim
  • 101
  • 1
  • 10
  • Not sure what is wrong with that (why you had to duplicate repositories, entityManagers, transactionsManagers), but continuing the Baeldung article, consider this: Have a class like EnvContext, with `public static ThreadLocal env = new ThreadLocal<>()`. In the Rest Controller, do `EnvContext.env.set(envQueryParam)`, in the `finally`: `EnvContext.env.clear()`. And in the `dataSource.setUrl` inside `@Bean public DataSource`, use `EnvContext.env.get()` – ShaharT Oct 11 '22 at 21:04
  • Does this answer your question? [Environment Specific application.properties file in Spring Boot application](https://stackoverflow.com/questions/32196451/environment-specific-application-properties-file-in-spring-boot-application) – pringi Oct 13 '22 at 11:11
  • I have solved this with JDBCTemplates but unfortunately haven't had time to check the suggested solution. Hope to try it next week – jazzyekim Oct 15 '22 at 20:00

0 Answers0