1

Use Case:

During JBoss server startup, one permanent database connection is already made using Spring Data JPA configurations(xml based approach).

Now when application is already up and running, requirement is to connect to multiple Database and connection string is dynamic which is available on run-time.

How to achieve this using Spring Data JPA?

Smart B0y
  • 423
  • 1
  • 5
  • 15

1 Answers1

0

One way to switch out your data source is to define a "runtime" repository that is configured with the "runtime" data source. But this will make client code aware of the different repos:

package com...runtime.repository;

public interface RuntimeRepo extends JpaRepository<OBJECT, ID> { ... }

@Configuration
@EnableJpaRepositories(
    transactionManagerRef="runtimeTransactionManager", 
    entityManagerFactoryRef="runtimeEmfBean")
@EnableTransactionManagement
public class RuntimeDatabaseConfig {

    @Bean public DataSource runtimeDataSource() {
        DriverManagerDataSource rds = new DriverManagerDataSource();
        // setup driver, username, password, url
        return rds;
    }

    @Bean public LocalContainerEntityManagerFactoryBean runtimeEmfBean() {
        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
        factoryBean.setDataSource(runtimeDataSource());
        // setup JpaVendorAdapter, jpaProperties, 
        return factoryBean;
    }

    @Bean public PlatformTransactionManager runtimeTransactionManager() {
        JpaTransactionManager jtm = new JpaTransactionManager();
        jtm.setEntityManagerFactory(runtimeEmfBean());
        return jtm;
    }
}

I have combined the code to save space; you would define the javaconfig and the repo interface in separate files, but within the same package.

To make client code agnostic of the repo type, implement your own repo factory, autowire the repo factory into client code and have your repo factory check application state before returning the particular repo implementation.

Shane Voisard
  • 1,145
  • 8
  • 12
  • We already have an existing xml based approach implemented in the application. When we try to integrate the above mentioned solution in the application, we get the following exception; No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined: expected single matching bean but found 2 where in one EntityManagerFactory would be the one configured in our xml and other being the newly configured according to your solution. Any suggestions ? – Smart B0y Mar 26 '15 at 06:53
  • Have you tried autowiring by name instead of by type? See [understanding-spring-autowired-usage](http://stackoverflow.com/questions/19414734/understanding-spring-autowired-usage) – Shane Voisard Apr 01 '15 at 11:42