alexhak
alexhak

Reputation: 131

JPA: 2 databases: one "update", the other "create"

I want to use two database schemas: one with static data (which cannot be changed), the other with dynamic data (which will change constantly during the execution of the Spring application).

In application.properties I have prescribed the following:

spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/XXXXXX
spring.datasource.username=root
spring.datasource.password=root

spring.second-datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/YYYYYY
spring.second-datasource.username=root
spring.second-datasource.password=root

But what should I do now with the spring.jpa.hibernate.ddl-auto parameter?

For one scheme I want to install:

spring.jpa.hibernate.ddl-auto=create

And for the other (where the data is always static):

spring.jpa.hibernate.ddl-auto=update

or

spring.jpa.hibernate.ddl-auto=none

Upvotes: 0

Views: 81

Answers (1)

asgarov1
asgarov1

Reputation: 4098

You have an issue that you need two different datasources. You should define them as 2 different beans and autowire them seperately. For clarity it's advisable to also use 2 different properties files.

You can create a Configuration class and use specific properties file to populate fields like so:

@Configuration
@PropertySource("classpath:db.properties")
public class Config {

  @Value("${db.driverClassName}")
String driverClassName;

  @Value("${db.url}")
String url;

  @Value("${db.username}")
String username;

  @Value("${db.password}")
String password;


  @Bean("datasourceId")
  public DataSource dataSource() {
    var dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(driverClassName);
    dataSource.setUrl(url);
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    return dataSource;
  }



  @Bean
  public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(dataSource());
    sessionFactory.setPackagesToScan(
      { "com.foo.bar" });
    sessionFactory.setHibernateProperties(hibernateProperties());

    return sessionFactory;
  }

  private final Properties hibernateProperties() {
        Properties hibernateProperties = new Properties();
    hibernateProperties.setProperty(
      "hibernate.hbm2ddl.auto", "create-drop");    
    return hibernateProperties;
  }
}

Upvotes: 2

Related Questions