1、在properties配置多个数据源,推荐使用druid配置数据源和连接池
2、每个数据源创建一个数据源配置类,用于初始化数据源并注入spring
注意:一个系统只有能有一个数据源配置有 @Primary
,其他数据源配置不要使用 @Primary
注解。
1、主数据源
biz 数据库的数据源
package pro.gov.datacenter.core.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
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.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy;
import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy;
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.jdbc.core.JdbcTemplate;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import pro.gov.platform.base.repository.GenericJpaRepositoryImpl;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "bizEntityManagerFactory", // 配置连接工厂
transactionManagerRef = "bizTransactionManager", // 配置事物管理器
basePackages = {// repository包
"pro.gov.datacenter.biztable.catalog.repository"
},
repositoryBaseClass = GenericJpaRepositoryImpl.class
)
public class BizDataSourceConfig {
@Autowired
private JpaProperties jpaProperties;
@Value("${mysql.dialect}")
private String mysqlDialect;
@Bean(name = "bizDataSource")
@ConfigurationProperties(prefix = "spring.datasource.druid.biz")
@Primary
public DruidDataSource bizDataSource() {
return DruidDataSourceBuilder.create().build();
}
@Primary
@Bean(name = "bizEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBiz(EntityManagerFactoryBuilder builder,
@Qualifier("bizDataSource") DataSource bizDataSource) {
return builder
// 设置数据源
.dataSource(bizDataSource)
// 这个非常关键,没有这个配置,则spring.jpa.hibernate.ddl-auto不会生效,大坑
.properties(getVendorProperties())
// 设置实体类所在位置.扫描所有带有 @Entity 注解的类
.packages(
"pro.gov.datacenter.biztable.common.domain",
"pro.gov.datacenter.biztable.catalog.domain"
)
// Spring会将EntityManagerFactory注入到Repository之中.有了 EntityManagerFactory之后,
// Repository就能用它来创建 EntityManager 了,然后 EntityManager 就可以针对数据库执行操作
.persistenceUnit("bizPersistenceUnit")
.build();
}
@Primary
@Bean(name = "bizEntityManager")
public EntityManager entityManager(
@Qualifier("bizEntityManagerFactory") LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean) {
return localContainerEntityManagerFactoryBean.getObject().createEntityManager();
}
private Map<String, String> getVendorProperties() {
Map<String, String> properties = new HashMap<>();
properties.put("database", "mysql");
properties.put("hibernate.dialect", mysqlDialect);
// 设置命名策略, 比如数据库中字段名是: user_name, 则对应实体类中写成 userName
properties.put("hibernate.physical_naming_strategy", SpringPhysicalNamingStrategy.class.getName());
properties.put("hibernate.implicit_naming_strategy", SpringImplicitNamingStrategy.class.getName());
jpaProperties.setProperties(properties);
return jpaProperties.getProperties();
}
/**
* 配置平台事务管理器
*
* @param localContainerEntityManagerFactoryBean
* @return
*/
@Primary
@Bean(name = "bizTransactionManager")
public PlatformTransactionManager transactionManagerBiz(
@Qualifier("bizEntityManagerFactory") LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean) {
return new JpaTransactionManager(localContainerEntityManagerFactoryBean.getObject());
}
/**
* 使用jdbcTemplate时才配置
*
* @param bizDataSource
* @return
*/
@Primary
@Bean(name = "bizJdbcTemplate")
public JdbcTemplate bizJdbcTemplate(@Qualifier("bizDataSource") DataSource bizDataSource) {
return new JdbcTemplate(bizDataSource);
}
/**
* 使用queryDSL才配置
*
* @param adminEntityManager
* @return
*/
@Bean(name = "bizJPAQueryFactory")
@Autowired
@Primary
public JPAQueryFactory jpaQuery(@Qualifier("bizEntityManager") EntityManager adminEntityManager) {
return new JPAQueryFactory(adminEntityManager);
}
}
2、其他数据源
meta 数据库的数据源
package pro.gov.datacenter.core.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
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.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy;
import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import pro.gov.platform.base.repository.GenericJpaRepositoryImpl;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "metaEntityManagerFactory",
transactionManagerRef = "metaTransactionManager",
basePackages = {// repository包
"pro.gov.platform.datasubject.repository"
},
repositoryBaseClass = GenericJpaRepositoryImpl.class
)
public class MetaDataSourceConfig {
@Autowired
private JpaProperties jpaProperties;
@Value("${mysql.dialect}")
private String mysqlDialect;
@Bean(name = "metaDataSource")
@ConfigurationProperties(prefix = "spring.datasource.druid.meta")
public DruidDataSource druidDataSource() {
return DruidDataSourceBuilder.create().build();
}
@Bean(name = "metaEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
@Qualifier("metaDataSource")DataSource dataSource) {
return builder
.dataSource(dataSource)
.properties(getVendorProperties())
.packages(
"pro.gov.platform.common.domain"
) // 设置实体类所在位置
.persistenceUnit("metaPersistenceUnit")
.build();
}
@Bean(name = "metaEntityManager")
public EntityManager entityManager(
@Qualifier("metaEntityManagerFactory")LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean) {
return localContainerEntityManagerFactoryBean.getObject().createEntityManager();
}
private Map<String, String> getVendorProperties() {
Map<String,String> properties = new HashMap<>();
properties.put("database", "mysql");
properties.put("hibernate.dialect", mysqlDialect);
// 设置命名策略, 比如数据库中字段名是: user_name, 则对应实体类中写成 userName
properties.put("hibernate.physical_naming_strategy", SpringPhysicalNamingStrategy.class.getName());
properties.put("hibernate.implicit_naming_strategy", SpringImplicitNamingStrategy.class.getName());
jpaProperties.setProperties(properties);
return jpaProperties.getProperties();
}
@Bean(name = "metaTransactionManager")
public PlatformTransactionManager transactionManager(
@Qualifier("metaEntityManagerFactory")LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean) {
return new JpaTransactionManager(localContainerEntityManagerFactoryBean.getObject());
}
@Bean(name = "metaJdbcTemplate")
public JdbcTemplate jdbcTemplate(@Qualifier("metaDataSource")DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
3、两个数据源的数据库配置信息
# 数据源方言
mysql.dialect=org.hibernate.dialect.MySQLDialect
#########数据源配置开始###################################################################################################################################################
#biz数据源
spring.datasource.druid.biz.url=jdbc:mysql://192.168.10.55:3306/table_biz_dev?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
spring.datasource.druid.biz.username=root
spring.datasource.druid.biz.password=ENC(P7lSCxglsCHdoLBNFBCKEw)
spring.datasource.druid.biz.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.druid.biz.initial-size=1
spring.datasource.druid.biz.max-active=5
spring.datasource.druid.biz.min-idle=1
spring.datasource.druid.biz.max-wait=6000
spring.datasource.druid.biz.test-on-borrow=false
spring.datasource.druid.biz.test-on-return=false
spring.datasource.druid.biz.test-while-idle=true
spring.datasource.druid.biz.max-open-prepared-statements=20
#meta数据源
spring.datasource.druid.meta.url=jdbc:mysql://192.168.10.55:3306/table_meta_dev?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
spring.datasource.druid.meta.username=root
spring.datasource.druid.meta.password=ENC(P7lSCxglsCHdoLBNFBCKEw)
spring.datasource.druid.meta.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.druid.meta.initial-size=1
spring.datasource.druid.meta.max-active=5
spring.datasource.druid.meta.min-idle=1
spring.datasource.druid.meta.max-wait=6000
spring.datasource.druid.meta.test-on-borrow=false
spring.datasource.druid.meta.test-on-return=false
spring.datasource.druid.meta.test-while-idle=true
spring.datasource.druid.meta.max-open-prepared-statements=20
#########数据源配置结束###################################################################################################################################################