SpringBoot+Jpa項目配置雙數據源的實現
引言
今天為大家?guī)硪恍┓浅S杏玫膶崙?zhàn)技巧,比如在我們需要對兩個數據庫進行操作的時候而哦我們通常用的只是單數據庫查詢,這就觸及到知識盲點了,那么廢話不多說上代碼!
配置yml文件
server:
port: 8080
spring:
profiles:
active: dev
jackson:
time-zone: GMT+8
# 這里是我們的數據庫配置地方
datasource:
data1: #這里是數據庫一
driverClassName: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.0.77:3306/test1?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&autoReconnect=true&failOverReadOnly=false&rewriteBatchedStatements=true
username: root
password: 123
type: com.alibaba.druid.pool.DruidDataSource
data2: #這里是數據庫二
driverClassName: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.0.88:3306/test2?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&autoReconnect=true&failOverReadOnly=false&rewriteBatchedStatements=true
username: root
password: 123
type: com.alibaba.druid.pool.DruidDataSource
當然到這里肯定是沒有結束的,需要配置一些參數,否則啟動會報錯
創(chuàng)建數據源配置類
我們創(chuàng)建一個數據源的類,我們就給他取名為DataSourceConfig(這個名字自定義),在項目下創(chuàng)建一個包,方便管理

package com.eman.cdn.common.dataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
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;
/**
* @author https://blog.csdn.net/weixin_42782429?spm=1000.2115.3001.5343
* @date 2021/12/21 11:35
* <p>
* description 數據源配置
*/
@Configuration
public class DataSourceConfig {
# 這里是我們在yml文件配置的位置
private final static String DB_TEST1 = "spring.datasource.test1";
private final static String DB_TEST2= "spring.datasource.test1";
# 這個Bean名字子自定義只要不是重復的Bean名字就行了
@Bean(name = "test1Properties")
@Qualifier("test1Properties")
@Primary
@ConfigurationProperties(DB_TEST1)
public DataSourceProperties test1Properties() {
return new DataSourceProperties();
}
@Bean(name = "test1DataSource")
@Qualifier("test1DataSource")
@Primary
@ConfigurationProperties(prefix = DB_TEST1)
public DataSource test1DataSource() {
return test1Properties().initializeDataSourceBuilder().build();
}
@Bean(name = "test2Properties")
@Qualifier("test2Properties")
@ConfigurationProperties(DB_TEST2)
public DataSourceProperties test2Properties() {
return new DataSourceProperties();
}
@Bean(name = "test2DataSource")
@Qualifier("test2DataSource")
@ConfigurationProperties(prefix = DB_ANALYSIS)
public DataSource test2DataSource() {
return test2Properties().initializeDataSourceBuilder().build();
}
}
為每個數據庫創(chuàng)建配置類
由于需要用到Mybaitis-plus所以你得先導入Mybaitis-Plus的依賴
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.0</version>
</dependency>
package com.eman.xx.xxx.xx;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
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.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
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.sql.DataSource;
import java.util.Objects;
/**
* @author tongJie
* @date 2021/12/21 11:59
* <p>
* description 日志處理端數據庫配置
*/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
// 配置連接工廠
entityManagerFactoryRef = "tes1Factory",
// 配置事物管理器
transactionManagerRef = "tes1Transaction",
// 設置Jpa 的 repository所在位置
basePackages = {"com.xx.xx.xx.**.repository"}
)
// 設置掃描的mapper
@MapperScan(basePackages ="xx.xx.xx.test1.**.mapper", sqlSessionTemplateRef = "tes1SqlSessionTemplate")
public class AnalysisDataBaseConfig {
@Autowired
@Qualifier("tes1DataSource")
private DataSource analysisDataSource;
@Autowired
private JpaProperties jpaProperties;
@Autowired
private HibernateProperties properties;
// 以下是jpa的配置
/**
* 連接工廠
* @param builder 創(chuàng)建工具
* @return 結果
*/
@Bean(name = "tes1Factory")
public LocalContainerEntityManagerFactoryBean tes1Factory(EntityManagerFactoryBuilder builder) {
return builder
// 設置數據源
.dataSource(analysisDataSource)
//設置實體類所在位置.掃描所有帶有 @Entity 注解的類
.packages("xx.xx.xx.tes1.**.entity")
// Spring會將EntityManagerFactory注入到Repository之中.有了 EntityManagerFactory之后,
// Repository就能用它來創(chuàng)建 EntityManager 了,然后 EntityManager 就可以針對數據庫執(zhí)行操作
.persistenceUnit("tes1")
// 為了加載yml中jpa下hibernate的相關配置
.properties(properties.determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings()))
.build();
}
/**
* 配置事物管理器
*
* @param builder 創(chuàng)建工具
* @return 結果
*/
@Bean(name = "tes1Transaction")
PlatformTransactionManager tes1Transaction(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(Objects.requireNonNull(analysisFactory(builder).getObject()));
}
// 以下是mybatis的配置
/**
* 配置sqlSessionFactory
* @return 結果
* @throws Exception 異常
*/
@Bean("tes1SqlSessionFactory")
public SqlSessionFactory tes1SqlSessionFactory() throws Exception {
MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
sqlSessionFactory.setDataSource(analysisDataSource);
sqlSessionFactory.setMapperLocations(new
//這里填寫你mybaits的xml文件存放的路徑
PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/*.xml"));
return sqlSessionFactory.getObject();
}
/**
* 配置sqlSessionTemplate
* @return 結果
*/
@Bean(name = "tes1SqlSessionTemplate")
public SqlSessionTemplate tes1SqlSessionTemplate() throws Exception {
return new SqlSessionTemplate(tes1SqlSessionFactory());
}
}
以此類推之后每增加一個數據庫源就循環(huán)上面的方法
注意!!??!包一定要放對你配置的位置,否則不識別就會報錯?。。。。?!
到此這篇關于SpringBoot+Jpa項目配置雙數據庫源的實現的文章就介紹到這了,更多相關SpringBoot Jpa雙數據庫源內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Jenkins初級應用之Invoke?Phing?targets插件配置
這篇文章主要為大家介紹了Jenkins初級應用之Invoke?Phing?targets的插件配置,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步早日升職加薪<BR>2022-04-04
SpringBoot項目使用@Scheduled注解實現定時任務的方法
文章介紹了在SpringBoot項目中使用@Scheduled注解實現定時任務的三種方式:基于注解、基于接口和基于注解設定多線程定時任務,詳細講解了@Scheduled注解的使用方法、各個參數以及如何配置動態(tài)定時任務和多線程定時任務,感興趣的朋友一起看看吧2025-03-03
Intellij IDEA下Spring Boot熱切換配置
這篇文章主要介紹了Intellij IDEA下Spring Boot熱切換配置,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-08-08
SpringBoot創(chuàng)建maven多模塊項目實戰(zhàn)代碼
本篇文章主要介紹了SpringBoot創(chuàng)建maven多模塊項目實戰(zhàn)代碼,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-09-09

