0

I have two databases that I connect to in my application.

I want to set up a dev-only profile that mocks these databases using an embedded H2 database, and I would like to have their schemas auto-created by using spring.jpa.generate-ddl=true. The entity classes for each database are in different java packages, which I hope might help me here.

Is such a thing possible using spring's autoconf mechanisms?

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
user636747
  • 127
  • 1
  • 11

1 Answers1

1

It is possible to use multiple databases in spring boot. But spring boot can automatically configure only one database. You need to configure the second database yourself.

@Bean
@ConfigurationProperties(prefix="second.datasource")
public DataSource secondDataSource(){
  return DataSourceBuilder
        .create()
        .driverClassName("org.h2.Driver")
        .build();

}

If you just need a jdbc connection, this would be already sufficient. As you want to use JPA you need also a second JPA configuration, that uses the second data source.

@Bean(name="secondEntityManager")
public LocalContainerEntityManagerFactoryBean mySqlEntityManagerFactory(EntityManagerFactoryBuilder builder,DataSource secondDataSource){
    return builder.dataSource(secondDataSource)                
        .packages("com.second.entity")
        .build();

}

You can find the code above and more in this post

Community
  • 1
  • 1
  • Thanks Stefan. I have managed to get this far on my own. My specific problem is trying to populate these embedded databases from my entity classes. I know I can use a schema.sql, but I'd like to do it from the entities. – user636747 Feb 27 '17 at 11:15