springBoot1.x版本的数据库连接池不是Hakari,在springBoot2.0版本以后才默认是Hakari,现在很多druid数据库连接池,但是他们的性能我并没有进行比较,所以还是使用Hakari连接池,springBoot2.x配置数据源和以前有少许不同,将会重点标出不同。
环境:springBoot2.1.4 jdk1.8 maven mysql
二 、项目结构
我的项目结构如下图:
三、配置文件
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.1.4.RELEASE
com.zgx
demo
0.0.1-SNAPSHOT
Communication
Demo project for Spring Boot
1.8
org.springframework.boot
spring-boot-starter-web
org.hibernate.javax.persistence
hibernate-jpa-2.1-api
1.0.0.Final
org.springframework.boot
spring-boot-starter-jdbc
org.apache.tomcat
tomcat-jdbc
mysql
mysql-connector-java
runtime
org.springframework.boot
spring-boot-starter-tomcat
provided
com.zaxxer
HikariCP
org.springframework.boot
spring-boot-maven-plugin
#第一个数据源
spring.datasource.primary.jdbc-url: jdbc:mysql://127。0.0.1:3306/communication?useUnicode=true&characterEncoding=utf-8
spring.datasource.primary.driver-class-name: com.mysql.cj.jdbc.Driver
spring.datasource.primary.username=root
spring.datasource.primary.password=123456
#第二个数据源
spring.datasource.secondary.jdbc-url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8
spring.datasource.secondary.driver-class-name: com.mysql.cj.jdbc.Driver
spring.datasource.secondary.username=root
spring.datasource.secondary.password=123456
# 下面为连接池的补充设置,应用到上面所有数据源中
#自动提交
spring.datasource.default-auto-commit=true
#指定updates是否自动提交
spring.datasource.auto-commit=true
spring.jpa.show-sql = true
spring.datasource.maximum-pool-size=100
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
spring.datasource.validation-query=SELECT 1
spring.datasource.test-on-borrow=false
spring.datasource.test-while-idle=true
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.time-between-eviction-runs-millis=18800
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto=update
#spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy
#spring.jpa.database=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
说明
<1> 数据库配置文件可以都放在application.properties文件中
<2>springBoot2.x使用JDBC连接数据库需要将url改为jdbc-url
<3>添加JDBC驱动名称由原来的com.mysql.jdbc.Driver改为
com.mysql.cj.jdbc.Driver
<4>配置多数据源和配置单数据源没有什么区别,使用primary和secondary来标注不同的数据源;(名字也可以换掉)
四、代码
1. DataSourceConfig.java
/**
* @Create Date: 2017年8月13日下午11:59:49
* @Version: V1.00
* @Author: 追到乌云的尽头找太阳
*/
@Configuration
@PropertySource("classpath:datasource.properties")
public class DataSourceConfig {
private Logger logger = LoggerFactory.getLogger(DataSourceConfig.class);
@Bean(name = "primaryDataSource")
@Primary
@Qualifier("primaryDataSource")
@ConfigurationProperties(prefix="spring.datasource.primary" )
public DataSource primaryDataSource() {
logger.info("第一个数据库连接池创建中.......");
return DataSourceBuilder.create().build();
}
@Bean(name = "secondaryDataSource")
@Qualifier("secondaryDataSource")
@ConfigurationProperties(prefix="spring.datasource.secondary")
public DataSource secondaryDataSource() {
logger.info("第二个数据库连接池创建中......");
return DataSourceBuilder.create().build();
}
}
说明:
<1>@PropertySource(“classpath:datasource.properties”)是用来获取数据库配置文件的,如果在application.properties中配置的话不需要此注解(PropertySource注解还是很好用的 )
<2> @ConfigurationProperties(prefix=“spring.datasource.primary” )是用来获取第一个数据源的配置参数
2. PrimaryDataSouceConfig.java
/**
* Company: B505信息技术研究所
* @Description: 第一个数据源的配置类
* @Create Date: 2017年5月11日下午9:22:12
* @Version: V1.00
* @Author: 追到乌云的尽头找太阳
*/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef="entityManagerFactoryPrimary",
transactionManagerRef="transactionManagerPrimary",
basePackages= { "com.zgx.dao" }) // 设置Repository所在位置
public class PrimaryDataSouceConfig {
@Autowired @Qualifier("primaryDataSource")
private DataSource primaryDataSource;
@Autowired
private HibernateProperties hibernateProperties;
@Autowired
private JpaProperties jpaProperties;
@Primary
@Bean(name = "entityManagerPrimary")
@ConfigurationProperties(prefix="spring.datasourse.primary")
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
}
@Primary
@Bean(name = "entityManagerFactoryPrimary")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary (EntityManagerFactoryBuilder builder) {
//springBoot2.x这样写就行了
Map propertiesMap= hibernateProperties.determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings());
return builder
.dataSource(primaryDataSource)
.properties(propertiesMap)
.packages("com.zgx.entity") // 设置实体类所在位置
.persistenceUnit("primaryPersistenceUnit")
.build();
}
/* // 此方法在springBoot2.x以上版本不适合了
private Map getVendorProperties(Datasorce datasorce) {
return jpaProperties.getHibernateProperties(datasorce);
}*/
@Primary
@Bean(name = "transactionManagerPrimary")
public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
}
}
/**
* Company: B505信息技术研究所
* @Description: 第二个数据源的配置类(entity和Dao所在位置)
* @Create Date: 2017年5月11日下午9:22:12
* @Version: V1.00
* @Author:追到乌云的尽头找太阳
*/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef="entityManagerFactorySecondary",
transactionManagerRef="transactionManagerSecondary",
basePackages= { "com.zgx.test.dao" }) // 设置Repository所在位置
public class SecondaryDataSouceConfig {
@Autowired @Qualifier("secondaryDataSource")
private DataSource secondaryDataSource;
@Autowired
private HibernateProperties hibernateProperties;
@Autowired
private JpaProperties jpaProperties;
@Primary
@Bean(name = "entityManagerSecondary")
@ConfigurationProperties(prefix="spring.datasourse.secondary")
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
}
@Primary
@Bean(name = "entityManagerFactorySecondary")
public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary (EntityManagerFactoryBuilder builder) {
Map propertiesMap= hibernateProperties.determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings());
return builder
.dataSource(secondaryDataSource)
.properties(propertiesMap)
.packages("com.zgx.test.entity") // 设置实体类所在位置
.persistenceUnit("secondaryPersistenceUnit")
.build();
}
/* // 此方法在springBoot2.1以上版本不适合了
private Map getVendorProperties() {
return jpaProperties.getHibernateProperties(new HibernateProperties());
}*/
@Primary
@Bean(name = "transactionManagerSecondary")
public PlatformTransactionManager transactionManagerSecondary(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactorySecondary(builder).getObject());
}
}
}
说明:不管是第一个数据源还是第二个数据源都需要设置实体类以及dao层;
<1> basePackages= { “com.zgx.dao” }) // 设置Repository所在位置
<2> .packages(“com.zgx.test.entity”) // 设置实体类所在位置
这两个一定要按照自己的实际情况进行修改;
<3>
private Map
return jpaProperties.getHibernateProperties(new HibernateProperties());
}
方法在springBoot2.x版本已经不再适用,可以参照上面代码修改即可,SpringBoot1.x和2.x配置数据源主要是这里发生里变化;
五、最后
在使用上述maven依赖时会发生一个mysql时区错误,这是由于版本问题,此问题我已经在我的上一篇博客进行了总结:
mysql 时区问题原因以及方法总结