Spring Data JPA | Dynamic runtime multiple database connection

非 Y 不嫁゛ 提交于 2019-12-24 10:41:45

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/29233726/spring-data-jpa-dynamic-runtime-multiple-database-connection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!