在项目中难免会有跨库操作的场景,此时就需要一个项目连接两个甚至多个数据源,以下说明spring boot多数据源的一些基本配置。
一、在pom.xml加入依赖jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
二、在application.yml 或application.properties文件中加入以下配置
spring:
datasource:
driverClassName: com.mysql.cj.jdbc.Driver
type: com.zaxxer.hikari.HikariDataSource
hikari:
maximum-pool-size: 5
primary-db:
url: jdbc:mysql://localhost:3306/db1?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8
username: root
password: 123456
second-db:
url: jdbc:mysql://localhost:3306/db2?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8
username: root
password: 654321
jpa:
database: MYSQL
show-sql: true
open-in-view: true
properties:
hibernate:
dialect: org.hibernate.dialect.MySQL5Dialect
hibernate:
dll-auto: none
三、添加主库配置文件DataSourcePrimaryConfig.java
package com.example.multidata.config;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Value;
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.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Properties;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(ent