Spring Boot(10)之 连接多个数据库(以两个数据库为例)

1、添加插件(pom.xml)

		
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-data-jpaartifactId>
		dependency>
		
		<dependency>
			<groupId>mysqlgroupId>
			<artifactId>mysql-connector-javaartifactId>
			<scope>runtimescope>
		dependency>

2、配置数据库(application.properties)

# MySql 数据库信息 本地数据库配置
spring.datasource.local.name=local_database
spring.datasource.local.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.local.jdbc-url=jdbc:mysql://localhost:3306/local_database?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true
spring.datasource.local.username=root
spring.datasource.local.password=
# MySql 数据库信息 线上数据库配置
spring.datasource.online.name=online_database
spring.datasource.online.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.online.jdbc-url=jdbc:mysql://localhost:3306/online_database?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true
spring.datasource.online.username=root
spring.datasource.online.password=

3、目录结构

Spring Boot(10)之 连接多个数据库(以两个数据库为例)_第1张图片

3.1、DataSourceConfiguration.java

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 javax.sql.DataSource;

@Configuration
public class DataSourceConfiguration {
    @Primary  // 主数据库
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.local")  // 上面第二步,数据库配置,见下图
    public DataSource localDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.online")  // 同上
    public DataSource onlineDataSource() {
        return DataSourceBuilder.create().build();
    }
}

Spring Boot(10)之 连接多个数据库(以两个数据库为例)_第2张图片

3.2、LocalConfig.java

注意:XXXX:表示需要根据具体情况修改。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
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;

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

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        basePackages = "com.XXXX.XXXX.sql.local", // Repository 所在 包的位置
        entityManagerFactoryRef = "entityManagerFactoryLocal",
        transactionManagerRef = "transactionManagerLocal")
public class LocalConfig {
//    @Autowired
//    @Qualifier("localDataSource")
    @Resource(name = "localDataSource")
    DataSource localDataSource;

    @Autowired
    JpaProperties jpaProperties;
    @Autowired
    private HibernateProperties hibernateProperties;

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

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

    @Primary
    @Bean(name = "entityManagerFactoryLocal")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryLocal(EntityManagerFactoryBuilder builder) {
        return builder.dataSource(localDataSource)
                .packages("com.XXXX.XXXX.db")  // 数据库 实体类 所在 包的位置
                .persistenceUnit("localPersistenceUnit")
                .properties(getVendorProperties())
                .build();
    }

//    @Primary
    @Bean(name = "transactionManagerLocal")
    public PlatformTransactionManager transactionManagerLocal(EntityManagerFactoryBuilder builder) {
        LocalContainerEntityManagerFactoryBean factoryOne = entityManagerFactoryLocal(builder);
        return new JpaTransactionManager(factoryOne.getObject());
    }
}

3.3、OnlineConfig.java

注意:XXXX:表示需要根据具体情况修改。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
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.annotation.Resource;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages= "com.XXXX.XXXX.sql.online", // Repository所在 包的位置
        entityManagerFactoryRef="entityManagerFactoryOnline",
        transactionManagerRef="transactionManagerOnline")
public class OnlineConfig {
//    @Autowired
//    @Qualifier("onlineDataSource")
    @Resource(name = "onlineDataSource")
    private DataSource onlineDataSource;
    @Autowired
    private JpaProperties jpaProperties;
    @Autowired
    private HibernateProperties hibernateProperties;

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

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

    @Bean(name = "entityManagerFactoryOnline")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryOnline(EntityManagerFactoryBuilder builder) {
        return builder.dataSource(onlineDataSource)
                .packages("com.XXXX.XXXX.db")  // 数据库 实体类 所在 包的位置
                .persistenceUnit("onlinePersistenceUnit")
                .properties(getVendorProperties())
                .build();
    }

    @Bean(name = "transactionManagerOnline")
    public PlatformTransactionManager transactionManagerOnline(EntityManagerFactoryBuilder builder) {
        LocalContainerEntityManagerFactoryBean factoryOne = entityManagerFactoryOnline(builder);
        return new JpaTransactionManager(factoryOne.getObject());
    }
}

3.4、LocalRepository.java

import com.XXXX.XXXX.db.Book;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface LocalRepository extends JpaRepository<Book, Integer>, JpaSpecificationExecutor<Book> {
    
}

3.5、OnlineRepository.java

import com.XXXX.XXXX.db.Book;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface OnlineRepository extends JpaRepository<Book, Integer>, JpaSpecificationExecutor<Book> {

}

4、测试(RepositoryTest)

import com.XXXX.XXXX.db.Book;
import com.XXXX.XXXX.sql.online.OnlineModel;
import com.XXXX.XXXX.sql.online.OnlineRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
class RepositoryTest {
    @Autowired
    LocalRepository lr;
    @Autowired
    OnlineRepository or;

    @Test
    public void test() {
        List<Book> lrList = lr.findAll();
        List<Book> orList = or.findAll();
    }
}

你可能感兴趣的:(数据库,spring,boot,java)