乐趣区

关于java:SpringBoot学习笔记配置多数据源

最近我的项目须要又从新温习了下 springboot,对于 springboot 配置多数据源,做了笔记,分享给有须要的小伙伴们,视频看的能源节点王鹤老师讲的,

能源节点王鹤老师解说的 springboot 教程,由浅入深,带你体验 Spring Boot 的极速开发过程,内容丰盛,涵盖了 SpringBoot 开发的方方面面,并且同步更新到 Spring Boot 2.x 系列的最新版本。

视频链接:
https://www.bilibili.com/vide…

一、目录构造

目录构造

二、依赖包(pom.xml)

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.2</version>
    </dependency>
</dependencies>

三、配置文件

server:
  port: 8080
spring:
  datasource:
    first:
      driver-class-name: com.mysql.jdbc.Driver
      jdbc-url: jdbc:mysql://localhost:3306/first?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true
      username: root
      password: root
    second:
      driver-class-name: com.mysql.jdbc.Driver
      jdbc-url: jdbc:mysql://localhost:3306/second?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true
      username: root
      password: root
  jpa:
    hibernate:
      ddl-auto: update
      naming:
        physical-strategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
        implicit-strategy: org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy
    show-sql: true
    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
    database: mysql

四、多数据源配置(jpa)

1. DataSourceConfiguration

package com.cetc.config;

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 {

    /**
     *  第一个数据连贯,默认优先级最高
     * @return
     */
    @Bean(name = "dataSourceFirst")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.first")
    public DataSource dataSourceFirst() {
        // 这种形式的配置默认只满足 spring 的配置形式,如果应用其余数据连贯(druid), 须要本人独立获取配置
        return DataSourceBuilder.create().build();
    }

    /**
     * 第二个数据源
     * @return
     */
    @Bean(name = "dataSourceSecond")
    @ConfigurationProperties(prefix = "spring.datasource.second")
    public DataSource dataSourceSecond() {return DataSourceBuilder.create().build();}
}

阐明:其实这里配置曾经实现了,这里就配置了两个数据源了。能够退出对应的 JdbcTemplate, 这里不做介绍,比较简单   

2. JpaFirstConfiguration

package com.cetc.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.domain.EntityScan;
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.annotation.EnableTransactionManagement;

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

/**
 * 第一个数据源,jpa 的相干配置
 */
@Configuration
@EntityScan(basePackages = "com.cetc.domain.first")
//1、实体扫描
//2、实体治理 ref
//3、事务管理
@EnableJpaRepositories(
        basePackages = "com.cetc.repository.first",
        entityManagerFactoryRef = "firstEntityManagerFactoryBean",
        transactionManagerRef = "firstTransactionManager")
@EnableTransactionManagement
public class JpaFirstConfiguration {

    // 第一个数据源,能够不加 Qualifier
    @Autowired
    @Qualifier("dataSourceFirst")
    private DataSource dataSource;

    //jpa 其余参数配置
    @Autowired
    private JpaProperties jpaProperties;

    // 实体治理工厂 builder
    @Autowired
    private EntityManagerFactoryBuilder factoryBuilder;

    /**
     * 配置第一个实体治理工厂的 bean
     * @return
     */
    @Bean(name = "firstEntityManagerFactoryBean")
    @Primary
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {return factoryBuilder.dataSource(dataSource)
                // 这一行的目标是退出 jpa 的其余配置参数比方(ddl-auto: update 等)// 当然这个参数配置能够在事务配置的时候也能够
                .properties(jpaProperties.getHibernateProperties(new HibernateSettings()))
                .packages("com.cetc.domain.first")
                .persistenceUnit("firstPersistenceUnit")
                .build();}

    /**
     * EntityManager 不过解释,用过 jpa 的应该都理解
     * @return
     */
    @Bean(name = "firstEntityManager")
    @Primary
    public EntityManager entityManager() {return entityManagerFactoryBean().getObject().createEntityManager();
    }

    /**
     * jpa 事务管理
     * @return
     */
    @Bean(name = "firstTransactionManager")
    @Primary
    public JpaTransactionManager transactionManager() {JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
        jpaTransactionManager.setEntityManagerFactory(entityManagerFactoryBean().getObject());
        return jpaTransactionManager;
    }
}

3. JpaSecondConfiguration

package com.cetc.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.domain.EntityScan;
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.annotation.EnableTransactionManagement;

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

/**
 * 第二个数据源,jpa 的相干配置
 */
@Configuration
@EntityScan(basePackages = "com.cetc.domain.second")
//1、实体扫描
//2、实体治理 ref
//3、事务管理
@EnableJpaRepositories(
        basePackages = "com.cetc.repository.second",
        entityManagerFactoryRef = "secondEntityManagerFactoryBean",
        transactionManagerRef = "secondTransactionManager")
@EnableTransactionManagement
public class JpaSecondConfiguration {

    // 第二个数据源,必须加 Qualifier
    @Autowired
    @Qualifier("dataSourceSecond")
    private DataSource dataSource;

    //jpa 其余参数配置
    @Autowired
    private JpaProperties jpaProperties;

    // 实体治理工厂 builder
    @Autowired
    private EntityManagerFactoryBuilder factoryBuilder;

    /**
     * 配置第二个实体治理工厂的 bean
     * @return
     */
    @Bean(name = "secondEntityManagerFactoryBean")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {return factoryBuilder.dataSource(dataSource)
                .properties(jpaProperties.getHibernateProperties(new HibernateSettings()))
                .packages("com.cetc.domain.second")
                .persistenceUnit("secondPersistenceUnit")
                .build();}

    /**
     * EntityManager 不过解释,用过 jpa 的应该都理解
     * @return
     */
    @Bean(name = "secondEntityManager")
    public EntityManager entityManager() {return entityManagerFactoryBean().getObject().createEntityManager();
    }

    /**
     * jpa 事务管理
     * @return
     */
    @Bean(name = "secondTransactionManager")
    public JpaTransactionManager transactionManager() {JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
        jpaTransactionManager.setEntityManagerFactory(entityManagerFactoryBean().getObject());
        return jpaTransactionManager;
    }
}
退出移动版