JPA Connect to multiple datasources

 

Spring JPA Connect to multiple datasources :


Follow below steps if you are using Spring JPA and have multiple data sources.


In the application.properties file or application.yml file have the below properties : 


server.port: 8080

spring:

  datasource:

    url: jdbc:sqlserver://localhost:1433;databaseName=name;authenticationScheme=NTLM;integratedSecurity=true

    driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver

    username: ${database.username.ms}

    password: ${database.password.ms}

  datasource-secondary:

    url: jdbc:postgresql://localhost:5432/dbname

    username: ${database.username}

    password: ${database.password}

    driver-class-name: org.postgresql.Driver



  jpa:

    hibernate:

      ddl-auto: update




If you see in the above properties I’m using spring.datasource as primary data source and spring.datasource-secondary as the secondary data source.

Provide Url,Driver named and password for both data sources.


Then we need to create 2 config classes one for primary and other for secondary as below : 

We have to set some db properties like hibernate.dialect as in below code



@Configuration

@EnableTransactionManagement

@EnableJpaRepositories(

        entityManagerFactoryRef = "primaryEntityManagerFactory",

        transactionManagerRef = "primaryTransactionManager",

        basePackages = {“package name where you store primary entity classes”})

public class PrimaryDataSourceConfiguration {


    @Primary

    @Bean(name = "primaryDataSourceProperties")

    @ConfigurationProperties("spring.datasource")

    public DataSourceProperties primaryDataSourceProperties() {

        return new DataSourceProperties();

    }


    @Primary

    @Bean(name = "primaryDataSource")

    @ConfigurationProperties("spring.datasource.configuration")

    public DataSource primaryDataSource(@Qualifier("primaryDataSourceProperties") DataSourceProperties primaryDataSourceProperties) {

        return primaryDataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();

    }


    @Primary

    @Bean(name = "primaryEntityManagerFactory")

    public LocalContainerEntityManagerFactoryBean primaryEntityManagerFactory(

            EntityManagerFactoryBuilder primaryEntityManagerFactoryBuilder, @Qualifier("primaryDataSource") DataSource primaryDataSource) {


        Map<String, String> primaryJpaProperties = new HashMap<>();

        primaryJpaProperties.put("hibernate.dialect", "org.hibernate.dialect.SQLServer2012Dialect");

        primaryJpaProperties.put("hibernate.hbm2ddl.auto", "update");

        primaryJpaProperties.put("hibernate.naming.implicit-strategy", "org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl");

        primaryJpaProperties.put("hibernate.naming.physical-strategy","org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl");


        return primaryEntityManagerFactoryBuilder

                .dataSource(primaryDataSource)

                .packages("com.aexp.cets.ltiadatamigration.primary")

                .persistenceUnit("primaryDataSource")

                .properties(primaryJpaProperties)

                .build();

    }


    @Primary

    @Bean(name = "primaryTransactionManager")

    public PlatformTransactionManager primaryTransactionManager(

            @Qualifier("primaryEntityManagerFactory") EntityManagerFactory primaryEntityManagerFactory) {


        return new JpaTransactionManager(primaryEntityManagerFactory);

    }

}




@Configuration

@EnableTransactionManagement

@EnableJpaRepositories(

        entityManagerFactoryRef = "secondaryEntityManagerFactory",

        transactionManagerRef = "secondaryTransactionManager",

        basePackages = {"“package name where you store secondary data source entity classes”"})

public class SecondaryDataSourceConfiguration {


    @Bean(name = "secondaryDataSourceProperties")

    @ConfigurationProperties("spring.datasource-secondary")

    public DataSourceProperties secondaryDataSourceProperties() {

        return new DataSourceProperties();

    }


    @Bean(name = "secondaryDataSource")

    @ConfigurationProperties("spring.datasource-secondary.configuration")

    public DataSource secondaryDataSource(@Qualifier("secondaryDataSourceProperties") DataSourceProperties secondaryDataSourceProperties) {

        return secondaryDataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();

    }


    @Bean(name = "secondaryEntityManagerFactory")

    public LocalContainerEntityManagerFactoryBean secondaryEntityManagerFactory(

            EntityManagerFactoryBuilder secondaryEntityManagerFactoryBuilder, @Qualifier("secondaryDataSource") DataSource secondaryDataSource) {


        Map<String, String> secondaryJpaProperties = new HashMap<>();

        secondaryJpaProperties.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");

        secondaryJpaProperties.put("hibernate.hbm2ddl.auto", "update");


        return secondaryEntityManagerFactoryBuilder

                .dataSource(secondaryDataSource)

                .packages("com.aexp.cets.ltiadatamigration.secondary")

                .persistenceUnit("secondaryDataSource")

                .properties(secondaryJpaProperties)

                .build();

    }


    @Bean(name = "secondaryTransactionManager")

    public PlatformTransactionManager secondaryTransactionManager(

            @Qualifier("secondaryEntityManagerFactory") EntityManagerFactory secondaryEntityManagerFactory) {


        return new JpaTransactionManager(secondaryEntityManagerFactory);

    }

}



Once this is done , When you write entity classes on primary base package then spring associates them with primary data source and vice versa.


Comments

Popular posts from this blog

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: java.lang.NoSuchMethodError: 'boolean org.springframework.web.context.request.async.WebAsyncManager.isMultipartRequestParsed()'] with root cause java.lang.NoSuchMethodError: 'boolean org.springframework.web.context.request.async.WebAsyncManager.isMultipartRequestParsed()'

React Js : Text response is empty when using fetch