随便记录一下
环境配置
Spring boot (v2.4.1)
Spring Data JPA 2.4.1
Druid 1.2.4
参考:https://www.cnblogs.com/zuiyue_jing/p/12757307.html
与之前的多数据源配置相比,增加了一个DataSourceConfig.java,并且后面的JPAPrimaryConfig.java、JPASecondaryConfig.java里稍微修改了一些代码。
image.pngpom.xml
<!-- 引入 持久层框架Spring Data Jpa-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- 引入sql server的jdbc驱动 -->
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 引入数据库连接池druid的依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.4</version>
</dependency>
<!-- 引入lombok,使用一些注解如@Data,可实现Bean的getter和setter方法-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- 引入单元测试依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
appication.yml
server:
port: 9000
spring:
jpa:
# 当后台逻辑代码crud数据库时,后台日志打印sql
show-sql: true
properties:
hibernate:
format_sql: true
hibernate:
naming:
# 大小写敏感
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
#create: 每次应用启动的时候会重新根据实体建立表,之前的表和数据都会被删除。
#create-drop:和上面的功能一样,但是多了一样,就是在应用关闭的时候,也就是sessionFactory一关闭,会把表删除。
#update: 最常用的,第一次启动根据实体建立表结构,之后启动会根据实体的改变更新表结构,之前的数据都在。
#validate: (适用于生产环境)会验证创建数据库表结构,只会和数据库中的表进行比较,
# 不会创建新表,但是会插入新值,运行程序会校验实体字段与数据库已有的表的字段类型是否相同,不同会报错
ddl-auto: validate
datasource:
#使用alibaba druid 连接池、监控
type: com.alibaba.druid.pool.DruidDataSource
druid:
primary:
driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
username: xx
password: xx
url: jdbc:sqlserver://localhost:1433;DatabaseName=xxx;charset=UTF-8
secondary:
driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
username: xx
password: xx
url: jdbc:sqlserver://localhost:1433;DatabaseName=xxx;charset=UTF-8
initial-size: 2
min-idle: 5
max-active: 10
max-wait: 5000
validation-query: SELECT 1
test-on-borrow: false
test-while-idle: true
time-between-eviction-runs-millis: 18800
web-stat-filter:
enabled: true
exclusions: js,gif,jpg,png,css,ico,/druid/*
stat-view-servlet:
enabled: true
login-username: root
login-password: druid2021
配置类 DataSourceConfig.java
package com.xxx.employees.config;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
@Configuration
public class DataSourceConfig {
@Primary
@Bean(value = "primaryDataSource")
@ConfigurationProperties("spring.datasource.druid.primary") //spring.datasource.druid.primary为yml文件中数据源路径:primary
public DataSource dataSourceOne(){
return DruidDataSourceBuilder.create().build();
}
@Bean(value = "secondDataSource")
@ConfigurationProperties("spring.datasource.druid.secondary")//spring.datasource.druid.secondary为yml文件中数据源路径:secondary
public DataSource dataSourceTwo(){
return DruidDataSourceBuilder.create().build();
}
}
配置类 JPAPrimaryConfig.java
package com.xxx.employees.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
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.annotation.Resource;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;
/**
* 实现Spring Data JPA 多数据源(本应用涉及到两个数据库)配置的文件。
* 此处是主数据源的配置文件。
* Primary指的是主数据源。
* 若是进行二次开发,在本配置文件内,需要修改的地方已加注释。
* 此文件需要修改两个地方。
*/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "entityManagerFactoryPrimary",
transactionManagerRef = "transactionManagerPrimary",
basePackages = {"com.xxx.employees.repository.primary"} // 第一个数据源的 repository包 所在位置
)
public class JPAPrimaryConfig {
@Resource
private JpaProperties jpaProperties;
@Resource
private HibernateProperties hibernateProperties;
@Resource
@Qualifier("primaryDataSource")
private DataSource primaryDataSource;
@Primary
@Bean(name = "entityManagerPrimary")
public EntityManager entityManager(EntityManagerFactoryBuilder builder){
return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
}
@Primary
@Bean(name = "entityManagerFactoryPrimary")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary (EntityManagerFactoryBuilder builder){
Map<String , Object> properties =
hibernateProperties.determineHibernateProperties(
jpaProperties.getProperties(),
new HibernateSettings()
);
return builder.dataSource(primaryDataSource)
.properties(properties)
.packages("com.xxx.employees.domain.primary") // 第二个数据源的 domain实体类包 所在位置
.persistenceUnit("primaryPersistenceUnit")
.build();
}
@Primary
@Bean(name = "transactionManagerPrimary")
public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder){
return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
}
}
配置类 JPASecondaryConfig.java
package com.xxx.employees.config;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
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.annotation.Resource;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;
/**
* 实现Spring Data JPA 多数据源(本应用涉及到两个数据库)配置的文件。
* 此处是第二个数据源的配置文件。
* Second指的是第二个数据源。可自定义名字。
* 若是进行二次开发,在本配置文件内,需要修改的地方已加注释。
* 此文件需要修改两个地方。
*/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "entityManagerFactorySecondary",
transactionManagerRef = "transactionManagerSecondary",
basePackages = {"com.xxx.employees.repository.secondary"} // 第二个数据源的 repository包 所在位置
)
public class JPASecondaryConfig {
@Resource
private JpaProperties jpaProperties;
@Resource
private HibernateProperties hibernateProperties;
@Resource
@Qualifier("secondDataSource")
private DataSource secondaryDataSource;
@Bean(name = "entityManagerSecondary")
public EntityManager entityManager(EntityManagerFactoryBuilder builder){
return entityManagerFactorySecondary(builder).getObject().createEntityManager();
}
@Bean(name = "entityManagerFactorySecondary")
public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary (EntityManagerFactoryBuilder builder){
Map<String , Object> properties =
hibernateProperties.determineHibernateProperties(
jpaProperties.getProperties(),
new HibernateSettings()
);
return builder.dataSource(secondaryDataSource)
.properties(properties)
.packages("com.xxx.employees.domain.secondary") // 第二个数据源的 domain实体类包 所在位置
.persistenceUnit("secondaryPersistenceUnit")
.build();
}
@Bean(name = "transactionManagerSecondary")
public PlatformTransactionManager transactionManagerSecondary(EntityManagerFactoryBuilder builder){
return new JpaTransactionManager(entityManagerFactorySecondary(builder).getObject());
}
}
网友评论