Springboot整合JPA配置多数据源流程详解
作者:Buckletime
1. Maven
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- 数据库连接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.9</version> </dependency> <dependency> <groupId>com.oracle.database.jdbc</groupId> <artifactId>ojdbc8</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.16</version> </dependency>
2. 基本配置
DataSource
在基本配置中,我们首先来配置多数据源基本信息以及DataSource,首先在application.yml中添加如下配置信息:
spring:
datasource:
# oracle数据库配置
oracle:
driver-class-name: oracle.jdbc.driver.OracleDriver
url: jdbc:oracle:thin:@10.0.66.72:1521:orcl
username: test
password: test
# mysql数据库配置
mysql:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://10.0.66.60:3306/swap_business_db?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai
username: root
password: root
type: com.alibaba.druid.pool.DruidDataSource
# druid数据库连接池
druid:
filters: stat
initialSize: 5
maxActive: 20
maxPoolPreparedStatementPerConnectionSize: 20
maxWait: 60000
minEvictableIdleTimeMillis: 30000
minIdle: 5
poolPreparedStatements: false
testOnBorrow: false
testOnReturn: false
testWhileIdle: true
timeBetweenEvictionRunsMillis: 60000
#Oracle模式
validation-query: SELECT 1 FROM DUAL #用来检测连接是否有效的sql
#MySQL模式
validation-queryM: SELECT 1 #用来检测连接是否有效的sql
jpa:
hibernate:
ddl-auto: none
oracle-dialect: org.hibernate.dialect.Oracle10gDialect
mysql-dialect: org.hibernate.dialect.MySQL8Dialect
show-sql: false
接下来配置两个DataSource,如下:
@Configuration public class DataSourceConfig { @Bean @ConfigurationProperties(prefix = "spring.datasource.oracle") @Primary DataSource dsOracle() { return DruidDataSourceBuilder.create().build(); } @Bean @ConfigurationProperties(prefix = "spring.datasource.mysql") DataSource dsMysql() { return DruidDataSourceBuilder.create().build(); } }
注意:@Primary
,这个注解一定不能少,否则在项目启动时会出错,@Primary表示当某一个类存在多个实例时,优先使用哪个实例。
3. 多数据源配置
接下来配置Jpa的基本信息,这里两个数据源,分别在两个类中来配置,oracle和mysql配置如下:
3.1 JpaConfigOracle
@Configuration @EnableJpaRepositories(basePackages = "cn.piesat.dao.oracle", entityManagerFactoryRef = "localContainerEntityManagerFactoryBeanOracle", transactionManagerRef = "platformTransactionManagerOracle") public class JpaConfigOracle { @Autowired @Qualifier(value = "dsOracle") DataSource dsOracle; @Autowired JpaProperties jpaProperties; @Autowired private HibernateProperties hibernateProperties; @Value("${spring.jpa.hibernate.oracle-dialect}") private String oracleDialect; @Value("${spring.jpa.show-sql}") private String showSql; @Bean @Primary LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBeanOracle(EntityManagerFactoryBuilder builder) { return builder.dataSource(dsOracle) .packages("cn.piesat.model") .properties(getVendorProperties()) .persistenceUnit("pu1") .build(); } /** * 设置数据源属性 * * @return */ private Map<String, Object> getVendorProperties() { Map<String, String> map = new HashMap<>(); // 设置oracle数据库方言 map.put("hibernate.dialect", oracleDialect); map.put("show-sql", showSql); jpaProperties.setProperties(map); return hibernateProperties.determineHibernateProperties( jpaProperties.getProperties(), new HibernateSettings()); } /** * 配置事务管理器 * * @param builder * @return */ @Bean PlatformTransactionManager platformTransactionManagerOracle(EntityManagerFactoryBuilder builder) { LocalContainerEntityManagerFactoryBean factoryBeanOracle = localContainerEntityManagerFactoryBeanOracle(builder); return new JpaTransactionManager(factoryBeanOracle.getObject()); } }
配置说明:JpaProperties
是系统提供的一个实例,里边的数据就是我们在application.yml中配置的jpa相关的配置。HibernateProperties
用来手动设置数据源属性,例如定义不同的数据库方言。然后我们提供两个Bean,分别是LocalContainerEntityManagerFactoryBean
和PlatformTransactionManager
事务管理器,不同于MyBatis和JdbcTemplate,在Jpa中,事务一定要配置。在提供LocalContainerEntityManagerFactoryBean的时候,需要指定packages,这里的packages指定的包就是这个数据源对应的实体类所在的位置,另外在这里配置类上通过@EnableJpaRepositories
注解指定dao所在的位置,以及LocalContainerEntityManagerFactoryBean和PlatformTransactionManager分别对应的引用的名字。
这样第一个就配置好了,第二个基本和这个类似,主要有几个不同点:
- dao的位置不同
- persistenceUnit不同
- 相关bean的名称不同
3.2 JpaConfigMysql
@Configuration @EnableJpaRepositories(basePackages = "cn.piesat.dao.mysql", entityManagerFactoryRef = "localContainerEntityManagerFactoryBeanMysql", transactionManagerRef = "platformTransactionManagerMysql") public class JpaConfigMysql { @Autowired @Qualifier(value = "dsMysql") DataSource dsMysql; @Autowired JpaProperties jpaProperties; @Autowired private HibernateProperties hibernateProperties; @Value("${spring.jpa.hibernate.mysql-dialect}") private String mysqlDialect; @Value("${spring.jpa.show-sql}") private String showSql; @Bean LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBeanMysql(EntityManagerFactoryBuilder builder) { return builder.dataSource(dsMysql) .packages("cn.piesat.model") .properties(getVendorProperties()) .persistenceUnit("pu2") .build(); } /** * 设置数据源属性 * * @return */ private Map<String, Object> getVendorProperties() { Map<String, String> map = new HashMap<>(); // 设置mysql数据库方言 map.put("hibernate.dialect", mysqlDialect); map.put("show-sql", showSql); jpaProperties.setProperties(map); return hibernateProperties.determineHibernateProperties( jpaProperties.getProperties(), new HibernateSettings()); } /** * 配置事务管理器 * * @param builder * @return */ @Bean PlatformTransactionManager platformTransactionManagerMysql(EntityManagerFactoryBuilder builder) { LocalContainerEntityManagerFactoryBean factoryBeanMysql = localContainerEntityManagerFactoryBeanMysql(builder); return new JpaTransactionManager(factoryBeanMysql.getObject()); } }
4. Dao层接口
接下来,在对应位置分别提供相关的实体类和dao即可,注意:实体类可以共用,dao的位置不同
oracle接口:
package cn.piesat.dao.oracle; public interface TMasOrbitInfoDao extends JpaRepository<TMasOrbitInfo, String> { List<TMasOrbitInfo> findBySatelliteAndObservationDateBetween(String satellite, String start, String end); }
mysql接口:
package cn.piesat.dao.mysql; public interface SwapBusinessEfficiencyMainDao extends JpaRepository<SwapBusinessEfficiencyMain, String> { List<SwapBusinessEfficiencyMain> findByDataIdentifyAndDataTimeBetween(String identify, String start, String end); }
到此,所有的配置就算完成了,接下来就可以在Service中注入不同的Dao,不同的Dao操作不同的数据源。
到此这篇关于Springboot整合JPA配置多数据源流程详解的文章就介绍到这了,更多相关Springboot配置多数据源内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!