1、项目目录
2、pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.dwb</groupId>
<artifactId>spring-boot-multi-datasource</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-boot-multi-datasource</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.7</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<!--下面的依赖是热加载用的-->
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId>
<version>1.2.0.RELEASE</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
3、主数据源配置
package com.dwb.springbootmultidatasource.conf;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
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.Map;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "entityManagerFactoryPrimary",
transactionManagerRef = "transactionManagerPrimary",
basePackages = {"com.dwb.springbootmultidatasource.dao.primary"})
public class PrimaryConfig {
@Autowired
@Qualifier("primaryDataSource")
private DataSource primaryDataSource;
@Bean
@Primary
@Qualifier("primaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.primary")
public DataSource DataSource1() {
return DataSourceBuilder.create().build();
}
@Primary
@Bean
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
}
/**
* packages为entity位置,不同的数据库之间要区分
*
* @param builder
* @return
*/
@Primary
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(EntityManagerFactoryBuilder builder) {
return builder
.dataSource(primaryDataSource)
.properties(getVendorProperties(primaryDataSource))
.packages("com.dwb.springbootmultidatasource.entity.primary")
.persistenceUnit("primaryPersistenceUnit")
.build();
}
@Autowired
private JpaProperties jpaProperties;
/**
* @param dataSource 该参数在jdk1.8中有变化,不在是DataSource
* @return
*/
private Map getVendorProperties(DataSource dataSource) {
return jpaProperties.getHibernateProperties(dataSource);
}
@Primary
@Bean
public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
}
}
4、从数据源配置
package com.dwb.springbootmultidatasource.conf;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
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.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "entityManagerFactorySecondary",
transactionManagerRef = "transactionManagerSecondary",
basePackages = {"com.dwb.springbootmultidatasource.dao.second"})
public class SecondaryConfig {
@Autowired
@Qualifier("secondaryDataSource")
private DataSource secondaryDataSource;
@Bean
@Qualifier("secondaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.second")
public DataSource DataSource2() {
return DataSourceBuilder.create().build();
}
@Bean
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
return entityManagerFactorySecondary(builder).getObject().createEntityManager();
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary(EntityManagerFactoryBuilder builder) {
return builder
.dataSource(secondaryDataSource)
.properties(getVendorProperties(secondaryDataSource))
.packages("com.dwb.springbootmultidatasource.entity.second") //设置实体类所在位置
.persistenceUnit("secondaryPersistenceUnit")
.build();
}
@Autowired
private JpaProperties jpaProperties;
/**
* @param dataSource 该参数在jdk1.8中有变化,不在是DataSource
* @return
*/
private Map getVendorProperties(DataSource dataSource) {
return jpaProperties.getHibernateProperties(dataSource);
}
@Bean
PlatformTransactionManager transactionManagerSecondary(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactorySecondary(builder).getObject());
}
}
5、主entity
package com.dwb.springbootmultidatasource.entity.primary;
import javax.persistence.*;
import java.io.Serializable;
@Table(name = "test_info")
@Entity
public class PrimaryTest implements Serializable {
@Id
@GeneratedValue
@Column(name = "id")
private Integer id;
@Column(name = "age", columnDefinition = "int COMMENT '年龄'")
private Integer age;
@Column(name = "name", columnDefinition = "varchar(32) default null COMMENT '姓名'")
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "TestInfo{" +
"id=" + id +
", age=" + age +
", name='" + name + '\'' +
'}';
}
}
6、从entity
package com.dwb.springbootmultidatasource.entity.second;
import javax.persistence.*;
import java.io.Serializable;
@Table(name = "wechat_approval_flag")
@Entity
public class SecondTest implements Serializable {
@Id
@GeneratedValue
@Column(name = "id")
private Integer id;
@Column(name = "date")
private String date;
@Column(name = "flag")
private Boolean flag;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public Boolean getFlag() {
return flag;
}
public void setFlag(Boolean flag) {
this.flag = flag;
}
@Override
public String toString() {
return "SecondTest{" +
"id=" + id +
", date=" + date +
", flag=" + flag +
'}';
}
}
7、主dao
package com.dwb.springbootmultidatasource.dao.primary;
import com.dwb.springbootmultidatasource.entity.primary.PrimaryTest;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface PrimaryDao extends JpaRepository<PrimaryTest, Integer> {
}
8、从dao
package com.dwb.springbootmultidatasource.dao.second;
import com.dwb.springbootmultidatasource.entity.second.SecondTest;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface SecondDao extends JpaRepository<SecondTest, Integer> {
}
9、service操作
package com.dwb.springbootmultidatasource.service;
import com.dwb.springbootmultidatasource.dao.primary.PrimaryDao;
import com.dwb.springbootmultidatasource.dao.second.SecondDao;
import com.dwb.springbootmultidatasource.entity.primary.PrimaryTest;
import com.dwb.springbootmultidatasource.entity.second.SecondTest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class GetInfoService {
private static final Logger logger = LoggerFactory.getLogger(GetInfoService.class);
@Autowired
private PrimaryDao primaryDao;
@Autowired
private SecondDao secondDao;
public void getInfo() {
logger.info("service 开始,primary 开始...");
List<PrimaryTest> listPrimary = primaryDao.findAll();
logger.info("primary数据库数据:" + listPrimary.toString());
logger.info("primary 结束\nsecond 开始...");
List<SecondTest> listSecond = secondDao.findAll();
logger.info("second数据库数据:" + listSecond.toString());
logger.info("service 结束!");
}
}
10、application.yml资源文件
spring:
profiles:
active: prod
11、application-dev.yml数据库连接配置
spring:
profiles: dev
datasource:
primary:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://119.23.251.93/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&autoReconnect=true
name: root
password: 123456
maxActive: 20
initialSize: 1
maxWait: 600000
minidle: 1
timeBetweenEvictionRunsMillis: 600000
minEvictableidleTimeMillis: 300000
validationQuery: select 1
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20
second:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://119.23.251.93/attendance?useUnicode=true&characterEncoding=utf-8&useSSL=false&autoReconnect=true
name: root
password: 123456
maxActive: 20
initialSize: 1
maxWait: 600000
minidle: 1
timeBetweenEvictionRunsMillis: 600000
minEvictableidleTimeMillis: 300000
validationQuery: select 1
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20
dbcp2:
initial-size: 5
max-wait-millis: 600000
test-on-borrow: true
jpa:
database-platform: org.hibernate.dialect.MySQL5Dialect
# hibernate:
# ddl-auto: update
show-sql: true
12、test类
package com.dwb.springbootmultidatasource.service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest
@RunWith(SpringRunner.class)
public class GetInfoServiceTest {
@Autowired
private GetInfoService getInfoService;
@Test
public void getInfo() throws Exception {
getInfoService.getInfo();
}