One, a brief introduction

Configuring multiple data sources means that multiple databases can be used in a project, and data from different databases can be retrieved and updated without manually switching databases.

Source code address: github.com/hanguilin/b…

Project environment: SpringBoot 2.1.9, Spring Data Jpa

Project Folder:

Second, the configuration

application.properties

  • Spring. The datasource. Primary. The driver – class – the name database driver package

  • Spring. The datasource. Primary. JDBC database connection url. –

  • Spring. The datasource. Primary username username

  • Spring. The datasource. Primary. “password,” password

The database configuration alias can be customized. In this case, the level-1 library is PrimMary. The secondary database is the same as the preceding.

Hikara is a database connection pool configuration, as well as Druid.

server.port=8080

########## Level-1 database configuration ##########spring.datasource.primary.driver-class-name=com.mysql.jdbc.Driver spring.datasource.primary.jdbc-url=jdbc:mysql://localhost:3306/primary_db? autoReconnect=true&useUnicode=true&useSSL=false
spring.datasource.primary.username=root
spring.datasource.primary.password=****
# Maximum number of connections
spring.datasource.primary.hikari.maximum-pool-size=20
Connection timed out in milliseconds
spring.datasource.primary.hikari.connection-timeout=60000
The lifetime of an idle connection is milliseconds
spring.datasource.primary.hikari.idle-timeout=60000
The lifetime of the connection is milliseconds
spring.datasource.primary.hikari.max-lifetime=60000
# verify connection validity milliseconds
spring.datasource.primary.hikari.validation-timeout=3000
Login timeout milliseconds
spring.datasource.primary.hikari.login-timeout=5
########## Level-1 database configuration ##########

########## Secondary database configuration ##########spring.datasource.secondary.driver-class-name=com.mysql.jdbc.Driver spring.datasource.secondary.jdbc-url=jdbc:mysql://localhost:3306/secondary_db? autoReconnect=true&useUnicode=true
spring.datasource.secondary.username=root
spring.datasource.secondary.password=****
# Maximum number of connections
spring.datasource.secondary.hikari.maximum-pool-size=20
Connection timed out in milliseconds
spring.datasource.secondary.hikari.connection-timeout=60000
The lifetime of an idle connection is milliseconds
spring.datasource.secondary.hikari.idle-timeout=60000
The lifetime of the connection is milliseconds
spring.datasource.secondary.hikari.max-lifetime=60000
# verify connection validity milliseconds
spring.datasource.secondary.hikari.validation-timeout=3000
Login timeout milliseconds
spring.datasource.secondary.hikari.login-timeout=5
########## Secondary database configuration ##########

# # # # # # # # # # hibernate configuration # # # # # # # # # #
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
# # # # # # # # # # hibernate configuration # # # # # # # # # #

Copy the code

DataSourcesConfig.java

  • @Bean(name = “primaryDataSource”)

Spring manages the returned object with the bean name primaryDataSource.

  • @Qualifier(“primaryDataSource”)

Inject the bean into the object by name.

  • @Primary

When more than one Bean candidate is present during autowiring, the Bean annotated as @primary is preferred, otherwise an exception is thrown.

  • @ConfigurationProperties(prefix=”spring.datasource.primary”)

The prefix for spring. The datasource. The configuration of the primary is injected into the corresponding to the name of the property field.

This class generates a two-level DataSource, which is managed by Spring for future calls from Spring.

package com.spring.security.config.datasource;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import com.zaxxer.hikari.HikariDataSource;

@Configuration
public class DataSourcesConfig {

    @Bean(name = "primaryDataSource")
    @Qualifier("primaryDataSource")
    @Primary
    @ConfigurationProperties(prefix="spring.datasource.primary")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create()
        		.type(HikariDataSource.class)
                .build();
    }

    @Bean(name = "secondaryDataSource")
    @Qualifier("secondaryDataSource")
    @ConfigurationProperties(prefix="spring.datasource.secondary")
    public DataSource secondaryDataSource() {
    	returnDataSourceBuilder.create() .type(HikariDataSource.class) .build(); }}Copy the code

PrimaryConfig.java

  • @Configuration

Register as a bean in Spring

  • @EnableTransactionManagement

Start transaction Management

@EnableJpaRepositories(         entityManagerFactoryRef=”entityManagerFactoryPrimary”,         transactionManagerRef=”transactionManagerPrimary”,         basePackages= { “com.spring.security.dao.primary” })

  • @EnableJpaRepositories

Annotations are used for Srping JPA code configuration in place of XML configuration files

  • entityManagerFactoryRef

Entity management factory, below is configured in the code base package for the com. Spring. Security. The entity. The primary

  • transactionManagerRef

Transaction management

  • basePackages

Persistence layer based package scanning, configured to com here. Spring. Security. Dao. The primary

The configuration of the two packages above means where the entities and DAO rub interfaces of the tier 1 database are located. When JPA does entity mapping, the entities under the corresponding package are mapped to the database that is not working. The DAO layer interface is also switched.

package com.spring.security.config.datasource;

import java.util.Map;

import javax.persistence.EntityManager;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef="entityManagerFactoryPrimary",
        transactionManagerRef="transactionManagerPrimary",
        basePackages= { "com.spring.security.dao.primary"}) public class PrimaryConfig {@autowired @qualifier ("primaryDataSource")
    private DataSource primaryDataSource;

    @Autowired(required=false)
    private JpaProperties jpaProperties;

    @Primary
    @Bean(name = "entityManagerPrimary")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
    }

    @Primary
    @Bean(name = "entityManagerFactoryPrimary")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary (EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(primaryDataSource)
                .properties(getVendorProperties())
                .packages("com.spring.security.entity.primary"PersistenceUnit ()"primaryPersistenceUnit")
                .build();
    }

    private Map<String, Object> getVendorProperties() {
        return jpaProperties.getHibernateProperties(new HibernateSettings());
    }

    @Primary
    @Bean(name = "transactionManagerPrimary")
    public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
        returnnew JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject()); }}Copy the code

SecondaryConfig.java

package com.spring.security.config.datasource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef="entityManagerFactorySecondary",
        transactionManagerRef="transactionManagerSecondary",
        basePackages= { "com.spring.security.dao.secondary"}) public class SecondaryConfig {@autowired private JpaProperties JpaProperties; @Autowired @Qualifier("secondaryDataSource")
    private DataSource secondaryDataSource;

    @Bean(name = "entityManagerSecondary")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return entityManagerFactorySecondary(builder).getObject().createEntityManager();
    }

    @Bean(name = "entityManagerFactorySecondary")
    public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary (EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(secondaryDataSource)
                .properties(getVendorProperties())
                .packages("com.spring.security.entity.secondary"PersistenceUnit ()"secondaryPersistenceUnit")
                .build();
    }

    private Map<String, Object> getVendorProperties() {
        return jpaProperties.getHibernateProperties(new HibernateSettings());
    }

    @Bean(name = "transactionManagerSecondary")
    PlatformTransactionManager transactionManagerSecondary(EntityManagerFactoryBuilder builder) {
        returnnew JpaTransactionManager(entityManagerFactorySecondary(builder).getObject()); }}Copy the code

If you need to scale more databases, you can add them yourself according to the above configuration.