Spring boot 配置多数据源(JPA)
1. MySql 数据库配置database1 和 database2.
database1:
create database database1;
use database1;
# 创建表
CREATE TABLE `tb_city` (
`cityId` int(11) NOT NULL AUTO_INCREMENT,
`cityName` varchar(255) DEFAULT NULL,
`cityIntroduce` varchar(255) DEFAULT NULL,
PRIMARY KEY (`cityId`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_city
-- ----------------------------
INSERT INTO `tb_city` VALUES ('1', '北京', '中国首都');
INSERT INTO `tb_city` VALUES ('2', '上海', '东方之珠');
INSERT INTO `tb_city` VALUES ('3', '南阳', '俺滴家乡');
database2:
create database database2;
Use database2;
## 创建表
DROP TABLE IF EXISTS `tb_house`;
CREATE TABLE `tb_house` (
`hosueId` int(11) NOT NULL AUTO_INCREMENT,
`houseName` varchar(255) DEFAULT NULL,
`houseIntroduce` varchar(255) DEFAULT NULL,
PRIMARY KEY (`hosueId`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_house
-- ----------------------------
INSERT INTO `tb_house` VALUES ('1', '蜗牛', '家就在身上');
INSERT INTO `tb_house` VALUES ('2', '三毛', '没有家');
2. 创建一个springboot 项目,引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-configuration-processor -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
3. 创建实体类
package com.zdy.springboot.entity.database1;
import lombok.Data;
import javax.persistence.*;
/**
* @author deyou
* @create 2020-03-29 6:22 PM
*/
@Entity
@Table(name="tb_city")
@Data
public class City {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int cityId;
private String cityName;
private String cityIntroduce;
}
package com.zdy.springboot.entity.database2;
import lombok.Data;
import javax.persistence.*;
/**
* @author deyou
* @create 2020-03-29 9:01 PM
*/
@Entity
@Table(name="tb_house")
@Data
public class House {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int hosueId;
private String houseName;
private String houseIntroduce;
}
4. 创建对应的Repository接口
package com.zdy.springboot.repository.database1;
import com.zdy.springboot.entity.database1.City;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* @author deyou
* @create 2020-03-29 9:18 PM
*/
public interface CityRepository extends JpaRepository<City,Integer> {
}
package com.zdy.springboot.repository.database2;
import com.zdy.springboot.entity.database2.House;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* @author deyou
* @create 2020-03-29 9:19 PM
*/
public interface HouseRepository extends JpaRepository<House,Integer> {
}
5. 配置application.yaml
spring:
datasource:
# 自定数据库
database1:
url: jdbc:mysql://localhost:3306/database1?useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
username: root
password: 666666
driverClassName: com.mysql.cj.jdbc.Driver
database2:
url: jdbc:mysql://localhost:3306/database2?useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
username: root
password: 666666
driverClassName: com.mysql.cj.jdbc.Driver
# type: com.alibaba.druid.pool.DruidDataSource
jpa:
database: mysql
show-sql: true
hibernate:
ddl-auto: update
naming:
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
database-platform: org.hibernate.dialect.MySQL5Dialect
6. 获取数据库配置类
package com.zdy.springboot.component;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
/**
* @author deyou
* @create 2020-03-29 5:43 PM
*/
@Component
@ConfigurationProperties(prefix = "spring.datasource.database1")
@Data
public class DataBase1Properties {
private String url;
private String username;
private String password;
private String driverClassName;
}
package com.zdy.springboot.component;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author deyou
* @create 2020-03-29 5:54 PM
*/
@Component
@ConfigurationProperties(prefix = "spring.datasource.database2")
@Data
public class DataBase2Properties {
private String url;
private String username;
private String password;
private String driverClassName;
}
7. 数据源配置
package com.zdy.springboot.config;
import com.zaxxer.hikari.HikariDataSource;
import com.zdy.springboot.component.DataBase1Properties;
import com.zdy.springboot.component.DataBase2Properties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
/**
* @author deyou
* @create 2020-03-29 5:58 PM
*/
//配置数据源 dataBase1 和 dataBase2
@Configuration
@Slf4j
public class DataSourceConfig {
@Autowired
private DataBase1Properties dataBase1Properties;
@Autowired
private DataBase2Properties dataBase2Properties;
//返回一个bean交给Spring 容器
@Bean(name = "dataBase1DataSource")
//主数据库
@Qualifier("dataBase1DataSource")
@Primary
public DataSource dataBase1DataSource(){
log.info("dataBase1DataSource初始化----111111");
//使用的是springboot2.0默认的Hikari连接
HikariDataSource dataSource = new HikariDataSource();
dataSource.setJdbcUrl(dataBase1Properties.getUrl());
dataSource.setUsername(dataBase1Properties.getUsername());
dataSource.setPassword(dataBase1Properties.getPassword());
dataSource.setDriverClassName(dataBase1Properties.getDriverClassName());
return dataSource;
}
@Bean(name = "dataBase2DataSource")
public DataSource dataBase2DataSource(){
log.info("dataBase2DataSource初始化----222222");
HikariDataSource dataSource = new HikariDataSource();
dataSource.setJdbcUrl(dataBase2Properties.getUrl());
dataSource.setUsername(dataBase2Properties.getUsername());
dataSource.setPassword(dataBase2Properties.getPassword());
dataSource.setDriverClassName(dataBase2Properties.getDriverClassName());
return dataSource;
}
}
8. 数据库配置类
主数据库
package com.zdy.springboot.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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.sql.DataSource;
/**
* @author deyou
* @create 2020-03-29 8:48 PM
*/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "entityManagerFactoryDataBase1", // 配置连接工厂
transactionManagerRef = "transactionManagerDatabase1", // 配置事务管理器
basePackages = {"com.zdy.springboot.repository.database1"} // 设置dao所在位置
)
public class DataBase1Config {
// 配置数据源
@Qualifier("dataBase1DataSource")
@Autowired
private DataSource dataSource;
@Primary
@Bean(name = "entityManagerFactoryDataBase1")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryDataBase1(EntityManagerFactoryBuilder builder) {
return builder
// 设置数据源
.dataSource(dataSource)
//设置实体类所在位置.扫描所有带有 @Entity 注解的类
.packages("com.zdy.springboot.entity.database1")
// Spring会将EntityManagerFactory注入到Repository之中.有了 EntityManagerFactory之后,
// Repository就能用它来创建 EntityManager 了,然后 EntityManager 就可以针对数据库执行操作
.persistenceUnit("database1PersistenceUnit")
.build();
}
/**
* 配置事物管理器
*
* @param builder
* @return
*/
@Bean(name = "transactionManagerDatabase1")
PlatformTransactionManager transactionManagerDatabase1(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactoryDataBase1(builder).getObject());
}
}
第二数据库
package com.zdy.springboot.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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.sql.DataSource;
/**
* @author deyou
* @create 2020-03-29 8:48 PM
*/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "entityManagerFactoryDataBase2", // 配置连接工厂
transactionManagerRef = "transactionManagerDatabase2", // 配置事物管理器
basePackages = {"com.zdy.springboot.repository.database2"} // 设置dao所在位置
)
public class DataBase2Config {
// 配置数据源
@Autowired
@Qualifier("dataBase2DataSource")
private DataSource dataSource;
@Bean(name = "entityManagerFactoryDataBase2")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryDataBase2(EntityManagerFactoryBuilder builder) {
return builder
// 设置数据源
.dataSource(dataSource)
//设置实体类所在位置.扫描所有带有 @Entity 注解的类
.packages("com.zdy.springboot.entity.database2")
// Spring会将EntityManagerFactory注入到Repository之中.有了 EntityManagerFactory之后,
// Repository就能用它来创建 EntityManager 了,然后 EntityManager 就可以针对数据库执行操作
.persistenceUnit("database2PersistenceUnit")
.build();
}
/**
* 配置事物管理器
*
* @param builder
* @return
*/
@Bean(name = "transactionManagerDatabase2")
PlatformTransactionManager transactionManagerDatabase2(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactoryDataBase2(builder).getObject());
}
}
9. 新建TestController类,进行测试
package com.zdy.springboot.controller;
import com.zdy.springboot.entity.database1.City;
import com.zdy.springboot.entity.database2.House;
import com.zdy.springboot.repository.database1.CityRepository;
import com.zdy.springboot.repository.database2.HouseRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @author deyou
* @create 2020-03-29 9:47 PM
*/
@RestController
public class TestController {
@Autowired
private CityRepository cityRepository;
@Autowired
private HouseRepository houseRepository;
//http://localhost:8080/getCity
@GetMapping(value = "/getCity")
public List<City> getCity(){
List<City> all = cityRepository.findAll();
return all;
}
//http://localhost:8080/getHouse
@GetMapping(value = "/getHouse")
public List<House> getHouse(){
List<House> all = houseRepository.findAll();
System.out.println(all);
return all;
}
}
分别访问Controller 内的2个网址查看数据成功,配置完成。
参考博客: https://blog.csdn.net/oschina_41790905/article/details/102994925
转载:https://blog.csdn.net/qq_21344887/article/details/105188838
查看评论