很多业务场景都需要使用到多数据库,本文介绍springboot对多数据源的使用。
这次先说一下application.properties文件,分别连接了2个数据库test和test1。完整代码如下:
端口号
server.port=8888
数据库url
spring.datasource.test.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false
数据库用户名
数据库密码
数据库驱动
数据库url
spring.datasource.test2.url=jdbc:mysql://localhost:3306/test2?characterEncoding=utf8&useSSL=false
数据库用户名
数据库密码
数据库驱动
控制台打印sql
然后说一下处理多数据源的DataSourceConfig,其中@ConfigurationProperties注解对应刚才的数据库,而且这个重点是一定要有一个主数据源,并且在上面加上@Primary,代码如下:
packagecom.liming.config;
importorg.springframework.beans.factory.annotation.Qualifier;
importorg.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
importorg.springframework.boot.context.properties.ConfigurationProperties;
importorg.springframework.context.annotation.Bean;
importorg.springframework.context.annotation.Configuration;
importorg.springframework.context.annotation.Primary;
importjavax.sql.DataSource;
/**
* @author liming
* @Description
* @project springboot_learn
* @package com.liming.config
* @email 394498036@qq.cn
* @date 2018/4/13
*/
@Configuration
public class DataSourceConfig {
@Bean(name="testDataSource")
@Qualifier("testDataSource")
@ConfigurationProperties(prefix="spring.datasource.test")
public DataSource primaryDataSource() {
returnDataSourceBuilder.create().build();
}
@Bean(name="test2DataSource")
@Qualifier("test2DataSource")
@Primary
@ConfigurationProperties(prefix="spring.datasource.test2")
public DataSource secondaryDataSource() {
returnDataSourceBuilder.create().build();
}
}
接下来是对应test数据库的配置,其中需要说一下的是@EnableJpaRepositories注解里面的basePackages属性对应的是这个数据源对应的repository(因为本文使用的是jpa), @Qualifier注解内的value要和DataSourceConfig的值一致即可。
代码如下:
packagecom.liming.config;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.beans.factory.annotation.Qualifier;
importorg.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
importorg.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
importorg.springframework.context.annotation.Bean;
importorg.springframework.context.annotation.Configuration;
importorg.springframework.context.annotation.Primary;
importorg.springframework.data.jpa.repository.config.EnableJpaRepositories;
importorg.springframework.orm.jpa.JpaTransactionManager;
importorg.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
importorg.springframework.transaction.PlatformTransactionManager;
importorg.springframework.transaction.annotation.EnableTransactionManagement;
importjavax.persistence.EntityManager;
importjavax.sql.DataSource;
importjava.util.Map;
/**
*@authorliming
*@Description
*@projectspringboot_learn
*@packagecom.liming.config
*@email394498036@qq.cn
*@date2018/4/10
*/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef="entityManagerFactoryPrimary",
transactionManagerRef="transactionManagerPrimary",
basePackages= {"com.liming.repository.datasource"})
publicclassTestDataSourceConfig{
@Autowired
@Qualifier("testDataSource")
privateDataSource dataSource;
@Primary
@Bean(name ="entityManagerPrimary")
publicEntityManager entityManager(EntityManagerFactoryBuilder builder) {
returnentityManagerFactoryPrimary(builder).getObject().createEntityManager();
}
@Primary
@Bean(name ="entityManagerFactoryPrimary")
publicLocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary (EntityManagerFactoryBuilder builder) {
returnbuilder
.dataSource(dataSource)
.properties(getVendorProperties(dataSource))
.packages("com.liming.entity.datasource")//设置实体类所在位置
.persistenceUnit("primaryPersistenceUnit")
.build();
}
@Autowired
privateJpaProperties jpaProperties;
privateMap getVendorProperties(DataSource dataSource) {
returnjpaProperties.getHibernateProperties(dataSource);
}
@Primary
@Bean(name ="transactionManagerPrimary")
publicPlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
returnnew JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
}
}
Test2DataSourceConfig就不多说了,和TestDataSourceConfig原理一致,代码如下:
packagecom.liming.config;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.beans.factory.annotation.Qualifier;
importorg.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
importorg.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
importorg.springframework.context.annotation.Bean;
importorg.springframework.context.annotation.Configuration;
importorg.springframework.data.jpa.repository.config.EnableJpaRepositories;
importorg.springframework.orm.jpa.JpaTransactionManager;
importorg.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
importorg.springframework.transaction.PlatformTransactionManager;
importorg.springframework.transaction.annotation.EnableTransactionManagement;
importjavax.persistence.EntityManager;
importjavax.sql.DataSource;
importjava.util.Map;
/**
*@authorliming
*@Description
*@projectspringboot_learn
*@packagecom.liming.config
*@email394498036@qq.cn
*@date2018/4/10
*/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef="entityManagerFactorySecondary",
transactionManagerRef="transactionManagerSecondary",
basePackages= {"com.liming.repository.datasource2"})//设置Repository所在位置
publicclassTest2DataSourceConfig{
@Autowired
@Qualifier("test2DataSource")
privateDataSource dataSource;
@Bean(name ="entityManagerSecondary")
publicEntityManager entityManager(EntityManagerFactoryBuilder builder) {
returnentityManagerFactorySecondary(builder).getObject().createEntityManager();
}
@Bean(name ="entityManagerFactorySecondary")
publicLocalContainerEntityManagerFactoryBean entityManagerFactorySecondary (EntityManagerFactoryBuilder builder) {
returnbuilder
.dataSource(dataSource)
.properties(getVendorProperties(dataSource))
.packages("com.liming.entity.datasource2")//设置实体类所在位置
.persistenceUnit("secondaryPersistenceUnit")
.build();
}
@Autowired
privateJpaProperties jpaProperties;
privateMap getVendorProperties(DataSource dataSource) {
returnjpaProperties.getHibernateProperties(dataSource);
}
@Bean(name ="transactionManagerSecondary")
PlatformTransactionManager transactionManagerSecondary(EntityManagerFactoryBuilder builder) {
returnnew JpaTransactionManager(entityManagerFactorySecondary(builder).getObject());
}
}
下面是对应的model和repository
City类
packagecom.liming.entity.datasource;
importjavax.persistence.*;
/**
*@authorliming
*@Description
*@projectspringboot_learn
*@packagecom.liming.Entity
*@email397600342@qq.com
*@date2018/4/7
*/
@Entity
@Table(name="city")
publicclassCity{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
privateintcityId;
privateString cityName;
privateString cityIntroduce;
publicCity(intcityId, String cityName, String cityIntroduce){
this.cityId = cityId;
this.cityName = cityName;
this.cityIntroduce = cityIntroduce;
}
publicCity(String cityName, String cityIntroduce){
this.cityName = cityName;
this.cityIntroduce = cityIntroduce;
}
publicCity(){
}
publicintgetCityId(){
returncityId;
}
publicvoidsetCityId(intcityId){
this.cityId = cityId;
}
publicStringgetCityName(){
returncityName;
}
publicvoidsetCityName(String cityName){
this.cityName = cityName;
}
publicStringgetCityIntroduce(){
returncityIntroduce;
}
publicvoidsetCityIntroduce(String cityIntroduce){
this.cityIntroduce = cityIntroduce;
}
}
House类
packagecom.liming.entity.datasource2;
importjavax.persistence.*;
/**
*@authorliming
*@Description
*@projectspringboot_learn
*@packagecom.liming.entity
*@email394498036@qq.cn
*@date2018/4/10
*/
@Entity
@Table(name="house")
publicclassHouse{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
privateinthouseId;
privateString houseName;
privateString houseIntroduce;
publicintgetHouseId(){
returnhouseId;
}
publicvoidsetHouseId(inthouseId){
this.houseId = houseId;
}
publicStringgetHouseName(){
returnhouseName;
}
publicvoidsetHouseName(String houseName){
this.houseName = houseName;
}
publicStringgetHouseIntroduce(){
returnhouseIntroduce;
}
publicvoidsetHouseIntroduce(String houseIntroduce){
this.houseIntroduce = houseIntroduce;
}
publicHouse(String houseName, String houseIntroduce){
this.houseName = houseName;
this.houseIntroduce = houseIntroduce;
}
}
CityRepository
packagecom.liming.repository.datasource;
importcom.liming.entity.datasource.City;
importorg.springframework.data.jpa.repository.JpaRepository;
/**
* @author liming
* @Description
* @project springboot_learn
* @package com.liming.Repository
* @email 397600342@qq.com
* @date 2018/4/7
*/
publicinterfaceCityRepositoryextendsJpaRepository {
}
HouseRepository
packagecom.liming.repository.datasource2;
importcom.liming.entity.datasource2.House;
importorg.springframework.data.jpa.repository.JpaRepository;
/**
* @author liming
* @Description
* @project springboot_learn
* @package com.liming.repository.datasource2
* @email 394498036@qq.cn
* @date 2018/4/10
*/
publicinterfaceHouseRepositoryextendsJpaRepository {
}
pom文件
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.liming
springboot_datasources
0.0.1-SNAPSHOT
jar
springboot_datasources
springboot_datasources
org.springframework.boot
spring-boot-starter-parent
1.5.9.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-data-jpa
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-devtools
runtime
mysql
mysql-connector-java
runtime
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-maven-plugin
因为上面这些都没什么可说的,都是和正常的写法没什么区别,最后是TestController测试类
packagecom.liming.controller;
importcom.liming.entity.datasource.City;
importcom.liming.entity.datasource2.House;
importcom.liming.repository.datasource.CityRepository;
importcom.liming.repository.datasource2.HouseRepository;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.web.bind.annotation.GetMapping;
importorg.springframework.web.bind.annotation.RestController;
/**
*@authorliming
*@Description
*@projectspringboot_learn
*@packagecom.liming.controller
*@email394498036@qq.cn
*@date2018/4/10
*/
@RestController
publicclassTestController{
@Autowired
CityRepository cityRepository;
@Autowired
HouseRepository houseRepository;
@GetMapping("/testDataSource")
publicString testDataSource(){
City city = new City("北京","中国首都");
cityRepository.save(city);
return"success";
}
@GetMapping("/testDataSource2")
publicString testDataSource2(){
House house = new House("豪宅","特别大的豪宅");
houseRepository.save(house);
return"success";
}
}
启动项目可以看到test数据库中新建了city表,test2数据库中新建了house表。
领取专属 10元无门槛券
私享最新 技术干货