0

I am having a spring boot application. It is having rest end points which are consumed by angular application. My application is hosted on tomcat server.

  1. myapp1.mydomain.com -> My War File -> database schema1
  2. myapp2.mydomain.com -> My War File -> database schema2
  3. myapp3.mydomain.com -> My War File -> database schema3

In this scenario I need to create multiple war file with just different database pointing but same code base.

Is it possible to decide at run time using the host name and then point to respective database schema.

I tried @primary but in it the repository is considered at run time, that is point to database 1 or 2 and code is written. With this approach I will have to recode all my spring data repository calls.

Abhijit C
  • 303
  • 3
  • 20

1 Answers1

0

Presume you are using hibernate, it allows you to specify the default schema by the property hibernate.default_schema.

You can define a HibernatePropertiesCustomizer bean to customize its value to the schema that you want based on the host name.

Something like :

@Bean
public HibernatePropertiesCustomizer hibernatePropertiesCustomizer(){
    return prop ->{
        prop.put("hibernate.default_schema" , determineSchema());
    };
}

private String determineSchema(){
   //implement the logic to determine schema from the hostname
}

For how to get the hostname using Java , you can refer to this.

Ken Chan
  • 84,777
  • 26
  • 143
  • 172
  • Thanks Ken, I am using Spring Data JPA and not sure how to inject data source during ingestion. Something like a interceptor before the controller and then based onhost name to pass data source. Can you help with any snippet? – Abhijit C Jul 23 '23 at 15:48
  • actually you will have different schema on the same DB or each schema on their own separate DB instance? please clarify. i originally think that your case is the former one – Ken Chan Jul 23 '23 at 16:30
  • you are right Ken, its different schema on same DB – Abhijit C Jul 23 '23 at 17:23